简体   繁体   English

如何改变 Javascript.map() function 中的原始数组?

[英]How to mutate original array in Javascript .map() function?

For eg:例如:

var persons = [{ "name":"A", "salary":1200 }, { "name":"B", "salary":"1500" }];

And you want to change the value of "salary" of each person in an original array.并且您想更改原始数组中每个人的“薪水”值。

If you want to mutate the original array, you can use Array#forEach function.如果你想改变原始数组,你可以使用Array#forEach函数。

 const persons = [{ "name":"A", "salary":1200 }, { "name":"B", "salary": 1500 }]; persons.forEach(item => item.salary += 1000); console.log(persons)

Array#map creates a new array of the created items and returns that. Array#map为创建的项目创建一个新数组并返回它。 After you need to assign the returned result.之后您需要分配返回的结果。

 let persons = [{ "name":"A", "salary":1200 }, { "name":"B", "salary": 1500 }]; persons = persons.map(item => { item.salary += 1000; return item; }); console.log(persons);

You can mutate the objects directly iterating with map.您可以直接使用 map 迭代来改变对象。 If I understood you correctly.如果我理解正确的话。

persons.map(i => { i.salary = i.salary * 1.25; return i; });
console.log(persons);
// [{ "name":"A", "salary": 1875 }, { "name":"B", "salary": 2343.75 }]

Though it's anti pattern and you should avoid performing mutations of your original array in map().虽然它是反模式,你应该避免在 map() 中执行原始数组的突变。

you can use a simple for loop for that你可以使用一个简单的 for 循环

 var persons = [{ "name":"A", "salary":1200 }, { "name":"B", "salary":"1500" }]; for(let element of persons){ element.salary*=2; } console.log(persons);

Use forEach.使用 forEach。 If your array is full of objects, and you simply want to mutate those objects — like in the original question — then you can simply have your callback function mutate the item passed to it in its first argument.如果您的数组充满了对象,而您只是想改变这些对象——就像在原始问题中一样——那么您可以简单地让回调函数改变在其第一个参数中传递给它的项目。

If your array is full of primitives, which can only be changed by assigning something else to the array slots, thereby mutating the array — or if for some other reason you want to reassign things to the array slots — you can still use forEach.如果您的数组充满原语,只能通过将其他内容分配给数组插槽来更改,从而改变数组 - 或者如果出于某些其他原因您想将内容重新分配给数组插槽 - 您仍然可以使用 forEach。 The second parameter and third parameters passed to the callback are the array index of the element currently being operated on, and a reference to the array itself.传递给回调的第二个参数和第三个参数是当前正在操作的元素的数组索引,以及对数组本身的引用。 So within the callback function, you can assign to the relevant array slot.所以在回调函数中,你可以分配给相关的数组槽。

.map() function takes third parameter in its callback thats the instance of original array. .map() 函数在其回调中采用第三个参数,即原始数组的实例。

You could do something like this also:你也可以做这样的事情:

 var persons = [{ "name":"A", "salary":1200 }, { "name":"B", "salary":1500 }]; persons.map(function(person, key, array) { array[key].salary *= 2; }); console.log(persons);

I read other answers, you can use any of them, but I see some problems there.我阅读了其他答案,您可以使用其中任何一个,但我发现那里存在一些问题。

I will mention 2 methodologies I have used in many different languages, map and forEach .我将提到我在许多不同语言中使用的两种方法, mapforEach map is a functional way of traversing a collection and creating some new collection with new (different or same) elements, independent of languages. map是一种遍历集合并使用新(不同或相同)元素创建一些新集合的功能方式,与语言无关。 With map , it is expected to create a new collection that is created by some mapping from initial collection.使用map ,预计会创建一个新集合,该集合是由初始集合的某些mapping创建的。 On the other hand, forEach is a method that eases traversing a collection by not using usual for loop syntax for collections, and mutating (or changing) each item if desired.另一方面, forEach是一种通过不使用通常的for循环语法来简化遍历集合的方法,并在需要时改变(或更改)每个项目。

If you use map on a collection that contains objects, and change those objects in the mapper function, you might face with unexpected behavior.如果您在包含对象的集合上使用map ,并在mapper函数中更改这些对象,您可能会遇到意外行为。 Beacuse you are changing directly the object you are operating on, and do not mapping it to another object.因为您正在直接更改您正在操作的对象,而不是mappingmapping到另一个对象。 This object might can be considered as a state and computers works based on the state transfers.这个对象可以被认为是一个state ,计算机基于状态转移工作。 If you want to change that object, ie some state, it is absolutely ok, but based on the description , you should not use map for such a case.如果你想改变那个对象,即某种状态,这绝对没问题,但根据描述,你不应该在这种情况下使用 map。 Because you are not creating a new array with some new values, but instead, mutating provided elements.因为您不是使用一些新值创建新数组,而是更改提供的元素。 Use forEach for such a case.对于这种情况,请使用forEach

I have added an example here .在这里添加了一个例子。 You can click the link and take a look at the console, and see my what I mean in a more clear way.您可以单击链接并查看控制台,并以更清晰的方式了解我的意思。

As far as I know, based on my experience, mutations in map method is considered as bad practice and discouraged.据我所知,根据我的经验, map方法中的突变被认为是不好的做法并且不鼓励。

These two are added for different purposes and it would be better to use them as expected.添加这两个是出于不同的目的,最好按预期使用它们。

For more, see Mozilla Web Docs page for Array .有关更多信息,请参阅Array 的 Mozilla Web 文档页面

JavaScript 有一个内置的 Array 方法映射,可以迭代 Array 的值

persons.map(person => person["salary"] + 1000)

尝试:

let persons = persons.map((person) => {person['salary'] = parseInt(person['salary']) + 1; return person})

If you have an array of primitives, you can use this function:如果你有一个基元数组,你可以使用这个 function:

function mapInplace<T>(arr: T[], callback: (v: T, i: number) => T) {
    for(const [i, v] of arr.entries()) {
        arr[i] = callback(v, i)
    }
}

Example usage:用法示例:

mapInplace(weights, w => w / total)

There's no return value since it's mutating the array.没有返回值,因为它正在改变数组。

 var persons = [{ "name":"A", "salary":1200 }, { "name":"B", "salary":"1500" }]; var mutatedPersons = persons.map(function(obj){ return {name:obj.name,salary:parseInt(obj.salary) + 100}; }) console.log(mutatedPersons);

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

相关问题 为什么这个映射函数不改变原始数组中的值? - Why does this map function not mutate the values in the original array? 在函数内部变换JavaScript数组 - Mutate JavaScript Array Inside Function 比较两个对象键数组,原始数组应在 javascript 中发生变异 - compare two array of objects keys, original array should mutate in javascript 您的 function 不应改变输入数组(Javascript) - Your function should not mutate the input array (Javascript) 大写名称 - 改变原始数组 - Capitalise names - Mutate original array Javascript Map函数不保留原始对象 - Javascript Map function does not preserve the original object 地图函数内部的charCodeAt()返回原始数组 - charCodeAt() inside map function returning original array 从多维数组中提取子数组并变异原始数组 V8 JavaScript - Extract subarray from a multidimensional array and mutate the original array V8 JavaScript 从多维数组中提取 Columns 的子数组并改变原始数组以删除这些列 JavaScript - Extract subarray of Columns from a multidimensional array and mutate the original array to remove those columns JavaScript 抽象是使用不改变原始数据并返回新数组的 Javascript 数组方法的一个因素吗? - Is abstraction a factor in using Javascript array methods that do not mutate original data and return a new array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM