Javascript用于将名称值对分配给对象的简写

时间:2016-01-30 08:57:26

标签: javascript

将名称值对添加到新对象时:

function example() {

   var address = {}; //I'd like to omit this line somehow, is it possible?
   var values = ["Dog", "Cat", "Giraffe", "Monkey", "Goose"]
   for (i=0; i <5; i++) {

      address[i] = values[i]

   }

}

是否有任何简写允许我省略上面评论的那一行?

2 个答案:

答案 0 :(得分:0)

您可以使用对象或数组文字语法或对象/数组方法创建该类型的数组。

数组数组:

// Using array literal grammar
var arr = [[value1, value2, value3], [value1, value2]]

// Creating and pushing to an array
var arr = [];
arr.push([value1, value2, value3]);

数组的对象:

  // Using object literal grammar
    var obj = { "key": [value1, value2, value3], "key2": [value1, value2] } 

    // Creating object properties using bracket or dot notation
    var obj = {};
    obj.key = [value1, value2, value3];
    obj["key2"] = [value1, value2]; 

答案 1 :(得分:0)

如果您正在寻找另一种方法来完成您的示例正在做的事情,您可以使用Array.prototype.reduce。如果你了解它是如何工作的,那么我认为它更清晰。

var vals = ["Dog", "Cat", "Giraffe", "Monkey", "Goose"];

function assignNameVal(arr){
    return arr.reduce(function(prev, curr, index, array){ 
      prev[index] = curr;        // curr is each element in arr for each iteration
      return prev;               // returned value is the prev arg for next execution in iteration
    }, {});                      // {} is first value of prev
}