简体   繁体   English

为什么这个 JavaScript 代码中的数组没有被改变?

[英]Why isn't the array being mutated in this JavaScript code?

This is my first question on Stackoverflow :)这是我关于 Stackoverflow 的第一个问题 :)

Below, I have set up two functions and I'm trying to use them to mutate the array "nums".下面,我设置了两个函数,我正在尝试使用它们来改变数组“nums”。 But it doesn't seem to work.但它似乎不起作用。 What am I doing wrong, especially in the last part after the function definitions?我做错了什么,尤其是在函数定义之后的最后一部分? I am using higher order functions to learn how they work.我正在使用高阶函数来了解它们的工作原理。

function forEach(array, callback) {
    for(let i=0; i<array.length; i++) {
    callback(array[i]);
  }
}

function mapWith(array, callback) {
    forEach(array, callback);
}

let nums = [1, 2, 3];
mapWith(nums, item => item+=2);
console.log(nums); //console output: [1, 2, 3]

But changing the last part the following way, does show that the array is changing the way I wanted.但是按照以下方式更改最后一部分确实表明数组正在改变我想要的方式。 But why can't I manipulate it directly?但是为什么不能直接操作呢?

let nums = [];
mapWith([1, 2, 3], item => nums.push(item+=2));
console.log(nums); //console output: [3, 4, 5]

The problem here seems to be that you are not saving your returned callback value for each array element.这里的问题似乎是您没有为每个数组元素保存返回的回调值。 You just need to modify your forEach() function like this你只需要像这样修改你的forEach()函数

function forEach(array, callback) {
    for(let i=0; i<array.length; i++) {
        array[i] = callback(array[i]);
  }
}
Side note 边注

Your mapWith function is doing nothing but calling your forEach function.您的mapWith函数除了调用您的forEach函数之外什么都不做。 You could just use forEach你可以只使用forEach

It works correctly, when you call callback(array[i]);当您调用callback(array[i]);时,它工作正常callback(array[i]); it passes value to callback function not reference, if you will pass for example an object to callback it will be passed as refernce.它将值传递给回调函数而不是引用,如果您将例如一个对象传递给callback ,它将作为引用传递。

An example:一个例子:

const obj = {val: 1};
const modify = (obj) => {
   obj.val += 1;
}

modify(obj);
console.log(obj);

This is what you are basically doing:这就是你基本上在做什么:

function callbackFunction (item) {
  return item + 2;
}
let test = 5;
const newNumber = callbackFunction(test);
console.log(test);
console.log(newNumber);

You don't mutate the variable test , but just return new variable.您不会改变变量test ,而只是返回新变量。 That's why you are getting the same numbers.这就是为什么你得到相同的数字。

Also, notice you wrote this mapWith(nums, item => item=+2);另外,注意你写了这个mapWith(nums, item => item=+2); instead of item += 2 .而不是item += 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM