开发者

Did (javascript's) splice somehow get changed/bugged in Firefox 4.0+?

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 l开发者_开发百科atest 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 []


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]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜