How do you assign a value inside a forEach loop?
本问题已经有最佳答案,请猛点这里访问。
我希望第一个console.log是[0,10,20,30],第二个是[0100,20,30]:
1 2 3 4 5 6 7 8 9 10 | 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 2 3 4 5 6 7 8 9 10 | 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; } } |
1 | .as-console-wrapper { max-height: 100% !important; top: 0; } |