【问题标题】:Prototype function polluting JavaScript array污染 JavaScript 数组的原型函数
【发布时间】:2013-05-01 16:34:59
【问题描述】:

我正在使用一个可以接受多个数组的 API,我在其中使用 apply() 来传递数组,但该数组包含一个原型函数,我似乎无法从单个数组中删除该函数。最终发生的是正在执行的原型函数。

这是原型函数: if ( !Array.prototype.last ) { Array.prototype.last = function(){ return this[this.length - 1]; }}

例如,当我记录每个数组时,我会在 eventList 数组中看到以下内容:

["name1", "index1", "value1", last: function]
["name2", "index2", "value2", last: function]
["name3", "index3", "value3", last: function]

然后我推送数组:

apiName.push.apply( apiName, eventList );

我尝试array.pop() 删除每个数组上的“last”函数,但无济于事。

原型函数最初是如何出现在数组中的,我如何防止它在 apply() 中被调用?

感谢您的任何见解!

【问题讨论】:

    标签: javascript arrays prototype apply


    【解决方案1】:

    数组是 JavaScript 中的对象。它们可以像对象一样具有属性和原型。

    例如:

    var a = [];
    a.foo = "bar";
    

    这是完全有效的。但是"bar" 在数组中吗?

    让我们问:

    console.log(a.length); // 0
    console.log(a.foo); // "bar"
    

    所以:,它不在数组中,但它确实作为对象的属性存在。

    就像使用属性向原型添加东西不会影响.length 的值。

    在记录时看到自定义原型有点遗憾(令人困惑),但我会将其归因于调试器中的自定义。

    【讨论】:

    • 使用 apply() 还会运行原型函数吗?
    • 不,apply() 仅运行您正在应用的功能。如果您改用concat() 可能会更容易? apiName = apiName.concat(eventList);
    猜你喜欢
    • 2016-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-25
    • 1970-01-01
    • 2016-10-04
    • 1970-01-01
    相关资源
    最近更新 更多