JavaScript中8个常见的陷阱
译者按:
原文: Who said javascript was easy ?
译者: Fundebug
为了保证可读性,本文采用意译而非直译。另外,本文版权归原作者所有,翻译仅用于学习。
这里我们针对JavaScript初学者给出一些技巧和列出一些陷阱。如果你已经是一个砖家,也可以读一读。
1. 你是否尝试过对数组元素进行排序?
[1,2,5,10].sort()
的结果是[1, 10, 2, 5]
。[1,2,5,10].sort((a, b) => a - b)
2. new Date() 十分好用
new Date()
的使用方法有:
- 不接收任何参数:返回当前时间;
x
- : 返回1970年1月1日 +
x
- 毫秒的值。
new Date(1, 1, 1)
- 返回1901年2月1号。
new Date(2016, 1, 1)
- 不会在1900年的基础上加2016,而只是表示2016年。
3. 替换函数没有真的替换?
|
如果你想把所有的b都替换掉,要使用正则:
|
4. 谨慎对待比较运算
|
===
来判断。
5. 数组不是基础类型
|
var
是否是数组,你需要使用Array.isArray(var)
。
6. 闭包
这是一个经典的JavaScript面试题:
|
虽然期望输出0,1,2,…,然而实际上却不会。知道如何Debug嘛?
有两种方法:
let
- 而不是
var
- 。备注:可以参考Fundebug的另一篇博客 ES6之”let”能替代”var”吗?
bind
- 函数。备注:可以参考Fundebug的另一篇博客 JavaScript初学者必看“this”
|
当然,还有很多解法。这两种是我最喜欢的!
7. 关于bind
下面这段代码会输出什么结果?
|
如果你说程序会崩溃,并且报错:Cannot read property ‘name’ of undefined。
因为第16行的geet
没有在正确的环境下执行。当然,也有很多方法解决这个BUG!bind
- 函数来解决问题:
|
greet
会被Foo的实例调用,而不是局部的函数的this
。greet
- 永远不会绑定到错误的作用域,你可以在构造函数里面使用
bind
- 来绑 。
|
- 你也可以使用箭头函数(=>)来防止作用域被修改。备注:可以参考Fundebug的另一篇博客 JavaScript初学者必看“箭头函数”。
|
8. Math.min()比Math.max()大
Math.min() < Math.max() // false |
因为Math.min() 返回 Infinity, 而 Math.max()返回 -Infinity。