我遇到了Array.splice()
函數的問題。當我將一個對象添加到一個數組中時,將它重新拼接出來,會丟失它的所有屬性。爲什麼?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?
請在此發佈您的代碼,以便我們不需要轉到其他鏈接。我已經爲你移動了它。 – 2012-03-11 20:56:37
好的,謝謝。對於那個很抱歉。我只是想有人可能想看到它的工作版本。 – 2012-03-11 20:58:02
你在一行寫了'mySplicedObj',然後在另一行寫了'mySpliceObj'。 – 2012-03-11 20:58:28