2016-12-04 288 views
1

我定义了一个对象,其中我添加了属性“Items”。我在.each函数中有这些数据,但它并没有用逗号来添加所有的数据。它只是将它切换出来。我究竟做错了什么?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

没有什么更显示 –

+0

我建议阅读有关教程[数据结构在JavaScript(http://eloquentjavascript.net/04_data.html)。 –

回答

0

数据属性不存储多个值。如果你想要这种行为,那么属性应该存储一个数组或一个对象。而且,如果是这样的话,你不会只是分配一个新值,因为(正如你发现的那样)只是覆盖旧值,你需要将数据输入到该数组中(例如)或者添加该对象的新属性。

// 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

@Lain严格来说,但实际上,当数组存在时,为什么要这么做呢?将数据存储为纯字符串对于数据传输非常重要(通过序列化),但当数组位于使用JSON的对象中时,可以顺序存储数组中存储的数据。 –