2016-12-04 3 views
1

プロパティ "Items"を追加したオブジェクトを定義しました。 .each関数内にそのデータがありますが、すべてのデータをコンマで追加するわけではありません。 1,2,3それだけでそれを切り替えます。私は間違って何をしていますか?Javascriptプロパティに複数の値を追加する

var data = {}; 
    $('.beauty').on('click', function(e){ 
     e.preventDefault(); 
     $('.selected').each(function(){ 
      data.Items = $(this).data('id'); 
     }); 
     $('.chosenTeam').each(function(){ 
      data.Team = $(this).data('team'); 
     }); 
     console.log(data); 
+0

私は[JavaScriptでデータ構造](http://eloquentjavascript.net/04_data.html)についてのチュートリアルを読むことをお勧めします –

+0

表示するよりは何もありません。 –

答えて

0

データプロパティには複数の値が格納されません。その振る舞いが必要な場合、プロパティは配列またはオブジェクトを格納する必要があります。そして、そうであれば、新しい値を割り当てるだけではなく、わかっているように古い値を上書きするだけなので、その配列にデータをpush(たとえば)追加するか、addオブジェクトの新しいプロパティ

// Here, were have a basic object with a single property (users) 
 
// and that property has the ability to store multiple values 
 
// because it is intialized to store an array 
 
var myObject = {users : []}; 
 

 
// For demonstration, we'll append new values into 
 
// the array stored in the users property 
 

 
// This is just an example of a data source that we'll want to draw from 
 
// In reality, this could be any data structure 
 
var userArray = ["Mary", "Joe", "John", "Alice", "Judy", "Steve"]; 
 

 
userArray.forEach(function(user){ 
 
    // The most important thing is to note that we are not trying to 
 
    // set the users property equal to anything (that would wipe out 
 
    // its old value in favor of the new value). We are appending new 
 
    // data into the object that the property is storing. 
 
    myObject.users.push(user); 
 
}); 
 

 

 
console.log(myObject.users); 
 

 
// Now, if I want to change one of the values stored in the users 
 
// property, I wouldn't just set the users property equal to that 
 
// new value because that would wipe out the entire array currently 
 
// stored there. We need to updated one of the values in the data 
 
// structure that is stored in the property: 
 
myObject.users[3] = "Scott"; // Change the 4th user to "Scott" 
 
console.log(myObject.users);

+0

ええと、私は配列を使いたいと思っていましたが、配列にプロパティを追加する方法を見つけることができないというのは馬鹿げているようです。 –

+0

文字列のためのよくあるデータプロパティは、文字列化されたデータを格納することができるため、すべてのデータも格納できます。 – Lain

+0

@Len実際には本当ですが、実際には配列が存在するときになぜこれをしたいのですか?データを純粋な文字列で保存することは(シリアル化を介して)データ送信には最適ですが、配列がJSONを使用してオブジェクト内にある場合、配列に格納されたデータをシリアル化する必要はありません。 –

関連する問題