您好,欢迎访问一九零五行业门户网

剖析JavaScript中8个常见的陷阱

javascript中8个常见的陷阱
分享: 
译者按: 漫漫编程路,总有一些坑让你泪流满面。
英文原文: who said javascript was easy ?
译者: fundebug
这里我们针对javascript初学者给出一些技巧和列出一些陷阱。如果你已经是一个砖家,也可以读一读。
1. 你是否尝试过对数组元素进行排序?
javascript默认使用字典序(alphanumeric)来排序。因此,[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. 替换函数没有真的替换?
let s = "bob"const replaced = s.replace('b', 'l')replaced === "lob" // 只会替换掉第一个bs === "bob" // 并且s的值不会变
如果你想把所有的b都替换掉,要使用正则:
"bob".replace(/b/g, 'l') === 'lol'
4. 谨慎对待比较运算
// 这些可以'abc' === 'abc' // true1 === 1 // true// 然而这些不行[1,2,3] === [1,2,3] // false{a: 1} === {a: 1} // false{} === {} // false
因为[1,2,3]和[1,2,3]是两个不同的数组,只是它们的元素碰巧相同。因此,不能简单的通过===来判断。·
5. 数组不是基础类型
typeof {} === 'object' // truetypeof 'a' === 'string' // truetypeof 1 === number // true// 但是....typeof [] === 'object' // true
如果要判断一个变量var是否是数组,你需要使用array.isarray(var)。
6. 闭包
这是一个经典的javascript面试题:
const greeters = []for (var i = 0 ; i < 10 ; i++) {greeters.push(function () { return console.log(i) })}greeters[0]() // 10greeters[1]() // 10greeters[2]() // 10
虽然期望输出0,1,2,…,然而实际上却不会。知道如何debug嘛?
有两种方法:
使用let而不是var。备注:可以参考fundebug的另一篇博客 es6之”let”能替代”var”吗?使用bind函数。备注:可以参考fundebug的另一篇博客 javascript初学者必看“this”greeters.push(console.log.bind(null, i))
当然,还有很多解法。这两种是我最喜欢的!
7. 关于bind
下面这段代码会输出什么结果?
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。
1、因为第16行的geet没有在正确的环境下执行。当然,也有很多方法解决这个bug!
我喜欢使用bind函数来解决问题:
//code from http://caibaojian.com/8-javascript-attention.htmlasyncgreet () {this.somethingasync().then(this.greet.bind(this))}
这样会确保greet会被foo的实例调用,而不是局部的函数的this。
2、如果你想要greet永远不会绑定到错误的作用域,你可以在构造函数里面使用bind来绑 。
class foo { constructor(name) { this.name = name this.greet = this.greet.bind(this) }}
3、你也可以使用箭头函数(=>)来防止作用域被修改。备注:可以参考fundebug的另一篇博客 javascript初学者必看“箭头函数”。
asyncgreet() { this.somethingasync().then(() = >{ this.greet() })}
8. math.min()比math.max()大
math.min() < math.max() // false
因为math.min()返回infinity, 而math.max()返回-infinity。
推荐教程:《js基础教程》
以上就是剖析javascript中8个常见的陷阱的详细内容。
其它类似信息

推荐信息