我正在 JVM 浏览器中运行一些 Javascript。我已经声明了一个原型(prototype)方法来帮助我插入非常大的数组
Array.prototype.extend = function (other_array) {
if (other_array === Array)
other_array.forEach(function (v) { this.push(v) }, this);
else
console.log("not an array");
}
调用时的工作方式是:
arrayA.extend(arrayB);
我知道我正在扩展数组。在一个环境中,一切都很好。在不同的环境中,该方法认为 arrayB 不是数组,这是错误的。
有什么线索吗?
编辑:阵列检查实际上在两种环境中都失败了。我的问题是在更新我的 JDK 后消失的 forEach 循环中抛出的 JDK 相关错误
最佳答案
if(other_array === Array)
几乎永远不会 工作,除非您传递的实际上是 window.Array
构造函数,例如:
arrayA.extend(Array); // this will fulfill the `if`, but it will then throw an error
// because the Array constructor has no forEach method
数组实例永远不会满足=== Array
。
但是您可以改用 Array.isArray
,这是一种可靠的跨环境检查方法是否为数组:
Array.prototype.extend = function (other_array) {
if(Array.isArray(other_array)) {
other_array.forEach(function(v) {this.push(v)}, this);
} else {
console.log("not an array");
}
}
关于javascript - 为什么js认为我的数组在某些环境下不是数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59605334/