如何使函数中的字符串工作?

时间:2017-10-05 20:08:32

标签: javascript

所以我试图让它工作.....我假设数组我不总是有类型和值这两个键。我正在尝试使该函数适用于多个不同的数组。这是我到目前为止的代码......

let inventory = [{
     type: "machine",
     value: 5300
 }, {
     type: "machine",
     value: 650
 }, {
     type: "duck",
     value: 20
 }, {
     type: "furniture",
     value: 1000
 }, {
     type: "duck",
     value: 25
 }, {
     type: "machine",
     value: 77
 }]

 function sum(x, y, z) {
     // store the total for each type
     let result = {};
     for (var i = 0; i < x.length; i++) {
         let item = x[i];
         let item_type = item['y'];
         if (result[item_type]) {
             result[item_type] += item['z'];
         }
         else {
             result[item_type] = item['z'];
         }
     }
     return result;
 }
 console.log(sum(inventory, 'type', 'value'))

2 个答案:

答案 0 :(得分:2)

您需要使用

item[y]

而不是item['y']item['z']也是如此,它变为item[z]

答案 1 :(得分:1)

您需要从'y'和'z'中删除单引号“'”。  在循环内部,您需要替换

让item_type = item ['y'];通过let item_type = item [y];等等

let inventory = [
  {type:   "machine", value: 5300},
  {type:   "machine", value:  650},
  {type:      "duck", value:   20},
  {type: "furniture", value: 1000},
  {type:      "duck", value:   25},
  {type:   "machine", value:   77}
]

function sum(x,y,z){
    console.log(x[1][y]);
    console.log(y);
    console.log(z);
// store the total for each type
   let result = {};
   for (var i = 0; i < x.length; i++) {
   let item = x[i];
   console.log(item);
   let item_type = item[y];
   if (result[item_type]) {
      result[item_type]+= item[y];
   }
   else  {
      result[item_type] = item[z];
   }
}
return result;
}

console.log(sum(inventory, 'type', 'value'))