(javascript 的)拼接在 Firefox 4.0 中是否以某种方式发生了更改/错误?

发布于 2024-11-05 23:20:14 字数 965 浏览 3 评论 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

隐诗 2024-11-12 23:20:14

Splice 返回删除的元素并修改旧的。您正在分配返回的元素(空数组)而不是 myArray。

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects /Array/splice

尝试类似的方法

var arrayOne = [1,2,3,4,5];
    arrayTwo = arrayOne.slice(0);

arrayTwo.splice(3,0,'Added')

console.log(arrayOne, arrayTwo); // [1, 2, 3, 4, 5] [1, 2, 3, "Added", 4, 5]

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

var arrayOne = [1,2,3,4,5];
    arrayTwo = arrayOne.slice(0);

arrayTwo.splice(3,0,'Added')

console.log(arrayOne, arrayTwo); // [1, 2, 3, 4, 5] [1, 2, 3, "Added", 4, 5]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文