在Array.prototype上添加函数时,例如
Array.prototype.distinct = function () {
console.log(this)
const map = {}
const result = []
for (const n of this) {
if (!(n in map)) {
map[n] = 1
result.push(n)
}
}
return result
}
[1,2,3,3,4,4].distinct()
这样执行就会报Uncaught TypeError: Cannot read property 'distinct' of undefined的错误,而把[1,2,3,3,4,4].distinct()换成var a = [1,2,3,3,4,4].distinct()时就不会报错,还有一个奇怪的地方是Array.prototype.distinct定义和[1,2,3,3,4,4].distinct()分开执行时不会报错,一起执行时也会报同样的错,这是什么原因
目测是分号问题!!!