Elliot Bonneville
Elliot Bonneville

Reputation: 53371

Array.splice() not behaving as expected

I'm having a issue with the Array.splice() function. When I add an object to an array, then splice it back out, it loses all its properties. Why?

Demo.

// create a new object named myObj, test to see if all properties are intact
var myObj = {
    prop1: 5,
    prop2: 3,
    prop3: 9
};

for(key in myObj) {
    document.write(key + " <br>");
}

// they are, prepare a break-line
document.write("---<br>");    

// okay, so I'm adding the object to a newly created array
var myArr = new Array();
myArr.push(myObj);

// watch what happens if I splice the obj back out of the array
var mySplicedObj = myArr.splice(0, 1);

// why doesn't this work?
document.write(mySpliceObj.prop1);

// this shows that myObj has lost all its properties when spliced!
for(key in mySplicedObj) {
    document.write(key);
}

// how is this happening, and why?
​

Upvotes: 1

Views: 162

Answers (1)

Bruno Silva
Bruno Silva

Reputation: 3097

splice() returns an array, you can access the object by using mySplicedObj[0].

Upvotes: 4

Related Questions