Array.splice()的行为不符合预期

时间:2012-03-11 20:54:33

标签: javascript arrays object

我遇到了Array.splice()功能的问题。当我将一个对象添加到数组中,然后将其拼接回来时,它会丢失所有属性。为什么呢?

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?
​

1 个答案:

答案 0 :(得分:4)

splice()返回一个数组,您可以使用mySplicedObj[0]

访问该对象