javascript - 意外的 JS 原型(prototype)行为

标签 javascript arrays

<分区>

我最近写了几个 JS 数组原型(prototype)的扩展

Array.prototype.diff = function (a) {
    return this.filter(function (i) {
        return !(a.indexOf(i) > -1);
    });
};

Array.prototype.udiff = function (a, b) {
    var rslt = this.concat(b);
    return rslt.filter(function (i) {
        return !(a.indexOf(i) > -1);
    });
};

那里没有什么特别令人兴奋的。但后来我遇到了一些非常不寻常的事情。这是一个例子

var arr = [];
for (prop in arr) {
    arr[prop].attrib = arr[prop].attrib.replaceAll('_', ' ', true);
}

一段看起来很无辜的代码,但它返回给我时出现了错误“undefined does not have method replaceAll - where replaceAll is my own String.prototype extension.

解决方案很简单——在操作 arr[prop] 之前发出

if ('string' == typeof(prop)) continue;

原因是 prop 也可以是 diffudiff。所以,问题解决了,但这种行为确实让我措手不及,不得不进行额外的 typeof 测试听起来很笨拙。也许这里有人对原型(prototype)扩展会发生什么有更深入的了解?

我应该提一下,所有这些问题都发生在 Windows 上的 Chrome 中。

最佳答案

参见 this answer详细解释


problem solved but this behavior did take me off my guard and having to do the additional typeof test does sound clumsy.

正确的方法是not to use for in loops on arrays但迭代它们直到它们的长度:

for (var i=0; i<arr.length; i++) {
    arr[i].attrib = arr[i].attrib.replaceAll('_', ' ', true);
}

关于javascript - 意外的 JS 原型(prototype)行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18658162/

相关文章:

javascript - jquery等高脚本

javascript - 有没有办法在 document.ready 之后允许 document.write ?

c - 尝试创建一个函数,使用冒泡排序对二维数组的行进行排序,然后打印出来

c - 如何使用 C 中的函数生成随机 float 数组

c - 试图理解 Knuth 的排列算法

javascript - 使用 html 从变量中删除样式标签

javascript - html() 似乎不适用于 li 中的 span 元素

javascript - 如何在悬停时显示 id div

python - 如何在 Python 中从 CSV 导入数组数组

c++ - 如何在类中使用数组?