Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/439.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在javascript中重新定义数组推送方法?_Javascript_Arrays - Fatal编程技术网

在javascript中重新定义数组推送方法?

在javascript中重新定义数组推送方法?,javascript,arrays,Javascript,Arrays,我是js的新手。 我在数组对象中重新定义了push()方法,如下所示 Array.prototype.push = function(item) { this[this.length] = '[' + item + ']'; return this; }; var arr = new Array(); arr.push('my'); console.debug(arr); console.debug(arr[0]); arr.push('name'); console.deb

我是js的新手。 我在数组对象中重新定义了push()方法,如下所示

Array.prototype.push = function(item) {
    this[this.length] = '[' + item + ']';
    return this;
};

var arr = new Array();
arr.push('my');
console.debug(arr);
console.debug(arr[0]);

arr.push('name');
console.debug(arr);
console.debug(arr[1]);

arr.push('is');
console.debug(arr);
console.debug(arr[2]);


// output

[] --> <1>
[my]
[] --> <2>
[name]
[] --> <3>
[is]
Array.prototype.push=函数(项){
此[this.length]='['+项+']';
归还这个;
};
var arr=新数组();
arr.push(“我的”);
控制台调试(arr);
console.debug(arr[0]);
arr.push(“名称”);
控制台调试(arr);
console.debug(arr[1]);
arr.push('is');
控制台调试(arr);
console.debug(arr[2]);
//输出
[] --> 
[我的]
[] --> 
[姓名]
[] --> 
[是]

但是我不明白为什么,,是空的。

如果删除要连接的括号,它会工作

push
在内部有一点调用,这可能就是它不工作的原因


此外,不应该有任何理由自己重新实现
push

尝试使用
console.debug(arr.join(',)而不是
控制台调试(arr)

如在

现在输出为

[my]
[my]
[my],[name]
[name]
[my],[name],[is]
[is]
在铬上测试


至于打印数组时
debug.console()
的奇怪行为,我怀疑它在构建输出字符串时也对数组使用push()。例如,如果您将
'['+item+'].
替换为
'
,则Firebug控制台中会出现一些异常,如中所示。

您是否有可能在chrome中调试?我也注意到了这一点。非常奇怪的行为。这似乎只发生在webkit浏览器中。我似乎不是这样。我刚刚在Chromium 10.0.648.133(Linux)中进行了测试,这个问题仍然很普遍。这是一篇内容丰富的文章,也是最肯定的答案。镀铬工具古怪。