1

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?
​
6
  • 1
    Please post your code here so we don't need to go to another link. I've moved it for you. Commented Mar 11, 2012 at 20:56
  • Okay, thanks. Sorry about that. I just thought somebody might want to see a working version of it. Commented Mar 11, 2012 at 20:58
  • 2
    You wrote mySplicedObj on one line and then mySpliceObj on another. Commented Mar 11, 2012 at 20:58
  • I suppose I did at that. Fixed, thanks. Commented Mar 11, 2012 at 21:00
  • 1
    Ah, good point. I'll keep that in mind for the next time I ask a question. :) Commented Mar 11, 2012 at 21:02

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

4 Comments

Oh, really? W3School's Javascript manual didn't reveal that, and neither did any of my Google or SO searches. Thanks!
@ElliotBonneville: Don't use w3schools as a source (w3fools.com), check out Mozilla's JS Docs (developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…).
@ElliotBonneville: Use console.log to check out what was returned by Array.splice.
Ooh, handy. I sure will. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.