Javascript:分配给对象或数组原型会导致括号不起作用

Javascript: Assigning to Object or Array Prototype Causes Brackets to Not Work

本文关键字:不起作用 原型 数组 分配 对象 Javascript      更新时间:2023-09-26

可能的重复项:
将函数添加到 javascript 的 Array 类分隔符中 for loops

在任何人说什么之前,我知道使用 Object.prototype 分配一些东西通常是不好的做法,但如果包含此代码块,我希望所有对象都具有这种东西。奇怪的是,当我使用 Array 时也会发生这种情况。这是在 Node.js 中进行的,所以它是在 V8 javascript 引擎中发生的。无论如何,这是怎么回事。我只是为这两种类型之一的原型分配一个函数(我已经单独尝试了这两种类型,但错误与结果相同,当我使用其他类型的类型时不会发生这种情况)。

Array.prototype.test = function() { console.log("test"); }
var a = ["test1", "test2", "test3"],
    index,
    entry;
a.test(); //prints 'test'
for(index in a) {
  entry = (a[index]).split("e"); //throws an error
}

错误是

Object Function () {console.log("test");} has no method 'split'

思潮?

如果你运行这个,你会看到发生了什么,因为你在数组上使用原型,该函数成为对象的一部分,并拆分抛出错误。

Array.prototype.test = function() { console.log("test"); }
var a = ["test1", "test2", "test3"],
    index,
    entry;
a.test(); //prints 'test'
for(index in a) {
    console.log(index);
    console.log(a);
//  entry = (a[index]).split("e"); //throws an error
}

你应该用以下命令迭代该数组:

for(index=0;index<a.length;index++)

因为当您添加成员时,它们将成为数组的一部分,因此使用

for(i in a) console.log(i);

这将打印所有键以及函数名称"test"

尝试

varTest = console.log("test");
Array.prototype.test = function() { varTest }
var a = ["test1", "test2", "test3"],
    index,
    entry;
a.test(); //prints 'test'
for(index in a) {
  entry = (a[index]).split("e"); //throws an error
}