简体   繁体   English

原型函数污染JavaScript数组

[英]Prototype function polluting JavaScript array

I'm working with an API that can accept multiple arrays in which I'm using apply() to pass the arrays, but the array contains a prototype function that I cannot seem to remove from the individual array. 我正在使用一个可以接受多个数组的API,在其中我使用apply()传递数组,但是该数组包含一个原型函数,我似乎无法从单个数组中删除它。 What ends up happening is that prototype function being executed. 最终发生的事情是原型函数正在执行。

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

For example when I log each array I see the following in my eventList array: 例如,当我记录每个数组时,我在eventList数组中看到以下内容:

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

I then push the arrays: 然后,我推数组:

apiName.push.apply( apiName, eventList );

I've tried array.pop() to remove the 'last' function on each array, but to no avail. 我试过array.pop()删除每个数组上的'last'函数,但无济于事。

How does the prototype function end up in the array in the first place and how would I prevent it from being called in the apply()? 原型函数首先如何在数组中结束,以及如何防止在apply()中调用它?

Thanks for any insight! 感谢您的见解!

Arrays are Objects in JavaScript. 数组是JavaScript中的对象。 They can have properties and prototypes just like an Object. 它们可以像对象一样具有属性和原型。

Ex: 例如:

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

This is completely valid. 这是完全有效的。 But is "bar" in the Array ? 但是"bar" 在数组中吗?

Let's ask: 我们去问问吧:

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

So: no , it's not in the Array but it does exist as a property of the Object. 所以: ,它不在数组中,但确实作为对象的属性存在。

Just like with properties adding things to the prototype doesn't affect the value of .length . 就像使用属性向原型添加东西一样,不会影响.length的值。

It's a bit unfortunate (confusing) that you see the custom prototype when logging, but I would attribute that to a customization in your debugger. 不幸的是,您在登录时看到了自定义原型,这有点令人困惑(困惑),但是我将其归因于调试器中的自定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM