1

如果我有这样的列表:

var a=  [['1'[0]],['2'[0]],['3'[0]],['4'[0]]];

如果条件应该另一个变量等于 '1','2','3','4' 然后增加它们列表的值,例如:

for(var i=0; i<a; i++{
 if(a[i] == z) {
   a[i] += z;
    }
}

我知道上面的代码行不通,但是我怎样才能让每个“内部”元素都起作用呢?

我是一个javascript新手,所以请原谅代码中的任何错误。

谢谢

4

2 回答 2

2

这些最里面的数组位于[1]第一组内部数组的索引处,假设您的数组的实际格式是:

// Note the commas between the inner elements which you don't have above.
var a = [['1',[0]],['2',[0]],['3',[0]],['4',[0]]];

所以你快到了,你需要访问a[i][1][0]和增加它++而不是+= z.

例子:

console.log(a[1][1][0]);
// 0  (at element '2')

// z is the string value you are searching for...
for(var i=0; i < a.length; i++) {
  // Match the z search at a[i][0]
  // because a[i] is the current outer array and [0] is its first element
  if(a[i][0] == z) {
    // Increment the inner array value which is index [i][1][0]
    // Because the 1-element inner array is at [i][1] and its first element is [0]
    a[i][1][0]++;
  }
}

所以对于z = '2'

// Flattened for readability:
a.toString();
// "1,0,2,1,3,0,4,0"
//-------^^^

然后z = '4'

// This time the '4' element gets incremented
a.toString();
// "1,0,2,1,3,0,4,1"
//-------^^^-----^^^

这是关于jsfiddle的演示......

更新:这是更新值所在的位置:

控制台示例

是的Array[1] 0: 1 增量值z == '4'

于 2012-12-09T14:47:38.720 回答
1

我不确定你想要完成什么,但我认为它是这样的:

var lists = {
    '1': [0],
    '2': [0]
};

function incrementList(listKey, value) {
    if (lists[listKey]) {
        lists[listKey] = lists[listKey].map(function(num) {
            return num + value;
        });
    }        
}

incrementList('1', 2);
console.log(lists['1'][0]); // 2

incrementList('1', 4);
console.log(lists['1'][0]); // 6

​</p>

于 2012-12-09T14:49:58.680 回答