Javascript 无法在数组上调用声明的原型函数
我在阵列上有以下原型:Javascript 无法在数组上调用声明的原型函数,javascript,arrays,prototype,Javascript,Arrays,Prototype,我在阵列上有以下原型: Array.prototype.testing = function(cb){ var that = this function a(i) { console.log(i) setTimeout(function() { if (i+1 >= that.length) { return cb() } else { a(i + 1)
Array.prototype.testing = function(cb){
var that = this
function a(i) {
console.log(i)
setTimeout(function() {
if (i+1 >= that.length) {
return cb()
} else {
a(i + 1)
}
}, 1000)
}
a(0)
}
当调用数组变量时,原型工作良好
var arr = [1,2,3]
arr.testing(function(){
console.log("Ended")
}) // Prints 1 2 3 Ended to the console
但当直接在数组上调用时,会抛出类型错误:
[1,2,3].testing(function(){
console.log("Ended")
}) // Throws an typeError on [1,2,3], undefined
了解为什么会出现这种情况有什么帮助吗?代码中没有任何错误。它在哪里抛出typeError???如果在前一行中没有包含分号,则
[
将被解释为试图访问前一表达式上的属性。在以[
,开头的行之前,请包含分号(
或任何可能是中缀或后缀运算符的操作。对于那些利用ASI的人来说,这是一种非常标准的做法。代码工作正常。代码没有错误