如何在forEach循环中分配值?

时间:2017-03-06 15:12:25

标签: javascript arrays

我预计第一个console.log为[0,10,20,30],第二个为[0,100,20,30]:



var arr = [0,10,20,30]
console.log(arr)
arr.forEach(each)
console.log(arr)

function each(data,index) {
   if (index === 1) {
      data = 100 // This isn't assigned to arr[1]
   }
}




1 个答案:

答案 0 :(得分:1)

您正在为本地变量分配值。要分配给实际索引,需要数组和索引,Array#forEach的回调API的参数二和三



var arr = [0,10,20,30]
console.log(arr)
arr.forEach(each)
console.log(arr)

function each(data,index, array) {
   if (index === 1) {
      array[index] = 100;
   }
}

.as-console-wrapper { max-height: 100% !important; top: 0; }