(javascript 的)拼接在 Firefox 4.0 中是否以某种方式发生了更改/错误?
根据 http://www.hunlock.com/blogs/Mastering_Javascript_Arrays ,这就是我所拥有的一直用作拼接数组的参考,
// Insert without deleting.
myArray=[1,2,3,4,5,6,7,8,9,10];
newArray = myArray.splice(5,0, '*');
newArray = myArray.splice(4,0, '*');
document.writeln(myArray); // outputs: 1,2,3,4,*,5,*,6,7,8,9,10
但是,在我的代码中,我有:
var myArray=[1,2,3,4,5,6,7,8,9,10];
var newArray = myArray.splice(5,0, '*');
console.log(newArray);
并且输出是 []
此外,我注意到 myArray 似乎随着 .splice 调用而改变,即使它被分配给新数组。
1)这是 Firefox 的一个错误吗? 2)是否有更好的方法来创建一个添加 1 个元素的新数组?
提前致谢!
编辑:刚刚注意到我的 console.log'ing 与示例中的有所不同...我的问题的第二部分仍然成立 - 我最近的尝试是:
var ints = [91, 44, 67, 80, 91, 52, 68, 50, 50, 32];
var weights = ints;
console.log(weights);
weights = weights.splice(1, 0, 'hey');
console.log(weights);
最终结果仍然是 []
According to http://www.hunlock.com/blogs/Mastering_Javascript_Arrays , which is what I have been using as a reference for splicing arrays,
// Insert without deleting.
myArray=[1,2,3,4,5,6,7,8,9,10];
newArray = myArray.splice(5,0, '*');
newArray = myArray.splice(4,0, '*');
document.writeln(myArray); // outputs: 1,2,3,4,*,5,*,6,7,8,9,10
however, in my code I have:
var myArray=[1,2,3,4,5,6,7,8,9,10];
var newArray = myArray.splice(5,0, '*');
console.log(newArray);
and the output is []
Furthermore, I noticed that it seems like myArray changes with a .splice call even though it's being assigned to newArray.
1) is this a bug with firefox?
2) is there a better way to create a new array with 1 added element?
Thanks in advance!
EDIT: just noticed I was console.log'ing something diffrent than in the example... the 2nd part of my question still holds true though - my latest try is:
var ints = [91, 44, 67, 80, 91, 52, 68, 50, 50, 32];
var weights = ints;
console.log(weights);
weights = weights.splice(1, 0, 'hey');
console.log(weights);
where the end result is still []
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Splice 返回删除的元素并修改旧的。您正在分配返回的元素(空数组)而不是 myArray。
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects /Array/splice
尝试类似的方法
Splice returns the elements removed and modifies the old. You're assigning the returned elements (an empty array) not the myArray.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice
Try something like