如何就地更改 JS 数组(如 Ruby“危险”方法,例如使用尾随!)
例子:
如果我有这个:
var arr = [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点:
arr === [2, 4, 6]
Run Code Online (Sandbox Code Playgroud)
(假设我有一个适当的函数可以将数字加倍)一步,而不需要再做任何变量?
使用Array.prototype.forEach(),第三个参数是this:输入数组
var arr = [1, 2, 3];
arr.forEach(function(el, index, array) {
array[index] = el * 2
});
console.log(arr)Run Code Online (Sandbox Code Playgroud)