2012-03-11 28 views
1

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

ここにコードを記入して、別のリンクに行く必要はありません。私はあなたのためにそれを移動しました。 –

+0

よろしくお願いいたします。申し訳ありません。私はちょうど誰かがそれの実際のバージョンを見たいかもしれないと思った。 –

+2

あなたは 'mySplicedObj'を1行に書き、次に' mySpliceObj'を別の行に書きました。 –

答えて

4

splice()配列を返し、あなたはmySplicedObj[0]を使用して、オブジェクトにアクセスすることができます。

+0

ああ、本当に? W3SchoolのJavascriptのマニュアルではそのことは明らかにされておらず、GoogleやSOの検索も行われていませんでした。ありがとう! –

+5

@ElliotBonneville:w3schoolsをソースとして使用しないでください(http://w3fools.com/)、MozillaのJS Docs(https://developer.mozilla.org/ja/JavaScript/Reference/Global_Objects/Array/splice )。 –

+0

Oho、チップのおかげで。私は今から自分のドキュメントを使用します。 –

関連する問題