Javascript向属性添加多个值

时间:2016-12-04 19:13:25

标签: javascript

我定义了一个对象,我添加了属性“Items”。我在.each函数中有这些数据,但它不会用逗号添加所有数据。 1,2,3它只是将其切换出来。我做错了什么?

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);

1 个答案:

答案 0 :(得分:0)

数据属性不存储多个值。如果您想要该行为,则该属性应存储数组或对象。而且,如果是这种情况,你不会只是分配一个新值,因为(正如你已经发现的那样)只是覆盖了旧的值,你需要将push数据放入该数组中(对于示例)或向对象添加新属性。

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