译者按: 漫漫编程路,总有一些坑让你泪流满面。javascript
原文: Who said javascript was easy ?java
译者: Fundebug面试
为了保证可读性,本文采用意译而非直译。另外,本文版权归原做者全部,翻译仅用于学习。编程
这里咱们针对JavaScript初学者给出一些技巧和列出一些陷阱。若是你已是一个砖家,也能够读一读。小程序
JavaScript默认使用字典序(alphanumeric)来排序。所以,[1,2,5,10].sort()
的结果是[1, 10, 2, 5]
。微信小程序
若是你想正确的排序,应该这样作:[1,2,5,10].sort((a, b) => a - b)
数组
new Date()
能够接收: - 不接收任何参数:返回当前时间; - 接收一个参数x
: 返回1970年1月1日 + x
毫秒的值。 - new Date(1, 1, 1)
返回1901年2月1号。 - 然而....,new Date(2016, 1, 1)
不会在1900年的基础上加2016,而只是表示2016年。微信
```js let s = "bob" const replaced = s.replace('b', 'l') replaced === "lob" // 只会替换掉第一个b s === "bob" // 而且s的值不会变 ``` 若是你想把全部的b都替换掉,要使用正则: ```js "bob".replace(/b/g, 'l') === 'lol' ```
```js // 这些能够 'abc' === 'abc' // true 1 === 1 // true // 然而这些不行 [1,2,3] === [1,2,3] // false {a: 1} === {a: 1} // false {} === {} // false ``` 由于[1,2,3]和[1,2,3]是两个不一样的数组,只是它们的元素碰巧相同。所以,不能简单的经过`===`来判断。
```js typeof {} === 'object' // true typeof 'a' === 'string' // true typeof 1 === number // true // 可是.... typeof [] === 'object' // true ``` 若是要判断一个变量`var`是不是数组,你须要使用`Array.isArray(var)`。
这是一个经典的JavaScript面试题: ```js const Greeters = [] for (var i = 0 ; i < 10 ; i++) { Greeters.push(function () { return console.log(i) }) } Greeters[0]() // 10 Greeters[1]() // 10 Greeters[2]() // 10 ``` 虽然指望输出0,1,2,...,然而实际上却不会。知道如何Debug嘛? 有两种方法: - 使用`let`而不是`var`。备注:能够参考Fundebug的另外一篇博客[ES6之"let"能替代"var"吗?](https://blog.fundebug.com/2017/05/04/why-you-should-not-use-var/) - 使用`bind`函数。备注:能够参考Fundebug的另外一篇博客[JavaScript初学者必看“this”](https://blog.fundebug.com/2017/05/17/javascript-this-for-beginners/) ```js Greeters.push(console.log.bind(null, i)) ``` 固然,还有不少解法。这两种是我最喜欢的!
bind
下面这段代码会输出什么结果? ```js class Foo { constructor (name) { this.name = name } greet () { console.log('hello, this is ', this.name) } someThingAsync () { return Promise.resolve() } asyncGreet () { this.someThingAsync() .then(this.greet) } } new Foo('dog').asyncGreet() ``` 若是你说程序会崩溃,而且报错:Cannot read property 'name' of undefined。 由于第16行的`geet`没有在正确的环境下执行。固然,也有不少方法解决这个BUG! - 我喜欢使用`bind`函数来解决问题: ```js asyncGreet () { this.someThingAsync() .then(this.greet.bind(this)) } ``` 这样会确保`greet`会被Foo的实例调用,而不是局部的函数的`this`。 - 若是你想要`greet`永远不会绑定到错误的做用域,你能够在构造函数里面使用`bind`来绑定。 ```js class Foo { constructor (name) { this.name = name this.greet = this.greet.bind(this) } } ``` - 你也可使用箭头函数(=>)来防止做用域被修改。备注:能够参考Fundebug的另外一篇博客[JavaScript初学者必看“箭头函数”](https://blog.fundebug.com/2017/05/25/arrow-function-for-beginner/)。 ```js asyncGreet () { this.someThingAsync() .then(() => { this.greet() }) } ```
```js Math.min() < Math.max() // false ``` 由于Math.min() 返回 Infinity, 而 Math.max()返回 -Infinity。
###关于Fundebug闭包
Fundebug专一于JavaScript、微信小程序、微信小游戏、支付宝小程序、React Native、Node.js和Java实时BUG监控。 自从2016年双十一正式上线,Fundebug累计处理了7亿+错误事件,获得了Google、360、金山软件、百姓网等众多知名用户的承认。欢迎免费试用!async
转载时请注明做者Fundebug以及本文地址: https://blog.fundebug.com/2017/06/28/who-said-js-was-easy/