Javascript 如何用Javascript替换数组中的项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5915789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:30:27  来源:igfitidea点击:

How to replace an item in an array with Javascript?

javascriptarrays

提问by James

Each item of this array is some number.

这个数组的每一项都是一些数字。

var items = Array(523,3452,334,31, ...5346);

How do I replace some number in with array with a new one?

如何用新的数组替换数组中的某些数字?

For example, we want to replace 3452 with 1010, how would we do this?

比如我们想把3452换成1010,怎么做呢?

回答by Eli

var index = items.indexOf(3452);

if (index !== -1) {
    items[index] = 1010;
}

Also it is recommend you not use the constructor method to initialize your arrays. Instead, use the literal syntax:

此外,建议您不要使用构造函数方法来初始化数组。相反,使用文字语法:

var items = [523, 3452, 334, 31, 5346];

You can also use the ~operator if you are into terse JavaScript and want to shorten the -1comparison:

~如果您喜欢简洁的 JavaScript 并想缩短-1比较,您也可以使用运算符:

var index = items.indexOf(3452);

if (~index) {
    items[index] = 1010;
}

Sometimes I even like to write a containsfunction to abstract this check and make it easier to understand what's going on. What's awesome is this works on arrays and strings both:

有时我什至喜欢写一个contains函数来抽象这个检查,让我更容易理解发生了什么。很棒的是,这适用于数组和字符串:

var contains = function (haystack, needle) {
    return !!~haystack.indexOf(needle);
};

// can be used like so now:
if (contains(items, 3452)) {
    // do something else...
}

Starting with ES6/ES2015 for strings, and proposed for ES2016 for arrays, you can more easily determine if a source contains another value:

从用于字符串的 ES6/ES2015 开始,并为用于数组的 ES2016 提议,您可以更轻松地确定源是否包含另一个值:

if (haystack.includes(needle)) {
    // do your thing
}

回答by gilly3

The Array.indexOf()method will replace the first instance. To get every instance use Array.map():

Array.indexOf()方法将替换第一个实例。要获取每个实例,请使用Array.map()

a = a.map(function(item) { return item == 3452 ? 1010 : item; });

Of course, that creates a new array. If you want to do it in place, use Array.forEach():

当然,这会创建一个新数组。如果您想就地进行,请使用Array.forEach()

a.forEach(function(item, i) { if (item == 3452) a[i] = 1010; });

回答by Shimon Agassi

My suggested solution would be:

我建议的解决方案是:

items.splice(1, 1, 1010);

The splice operation will remove 1 item, starting at position 1 in the array (i.e. 3452), and will replace it with the new item 1010.

拼接操作将删除 1 个项目,从数组中的位置 1 开始(即3452),并将用新项目替换它1010

回答by Tesserex

Use indexOf to find an element.

使用 indexOf 查找元素。

var i = items.indexOf(3452);
items[i] = 1010;

回答by mellamokb

Easily accomplished with a forloop.

for循环轻松完成。

for (var i = 0; i < items.length; i++)
    if (items[i] == 3452)
        items[i] = 1010;

回答by VirtualTroll

You can edit any number of the list using indexes

您可以使用索引编辑任意数量的列表

for example :

例如 :

items[0] = 5;
items[5] = 100;

回答by Yatrix

If using a complex object (or even a simple one) and you can use es6, Array.prototype.findIndexis a good one. For the OP's array, they could do,

如果使用复杂的对象(甚至是简单的对象)并且可以使用 es6,Array.prototype.findIndex则是一个不错的选择。对于 OP 的阵列,他们可以这样做,

const index = items.findIndex(x => x === 3452)
items[index] = 1010

For more complex objects, this really shines. For example,

对于更复杂的对象,这真的很闪耀。例如,

const index = 
    items.findIndex(
       x => x.jerseyNumber === 9 && x.school === 'Ohio State'
    )

items[index].lastName = 'Utah'
items[index].firstName = 'Johnny'

回答by Artee

Replacement can be done in one line:

替换可以在一行中完成:

var items = Array(523, 3452, 334, 31, 5346);

items[items.map((e, i) => [i, e]).filter(e => e[1] == 3452)[0][0]] = 1010

console.log(items);

Or create a function to reuse:

或者创建一个函数来重用:

Array.prototype.replace = function(t, v) {
    if (this.indexOf(t)!= -1)
        this[this.map((e, i) => [i, e]).filter(e => e[1] == t)[0][0]] = v;
  };

//Check
var items = Array(523, 3452, 334, 31, 5346);
items.replace(3452, 1010);
console.log(items);

回答by AmerllicA

ES6way:

ES6方式:

const items = Array(523, 3452, 334, 31, ...5346);

We wanna replace 3452with 1010, solution:

我们想替换34521010,解决方案:

const newItems = items.map(item => item === 3452 ? 1010 : item);

Surely, the question is for many years ago and for now I just prefer to use immutablesolution, definitely, it is awesome for ReactJS.

当然,问题是多年前的问题,现在我更喜欢使用不可变的解决方案,当然,它对于ReactJS.

For frequent usage I offer below function:

对于经常使用,我提供以下功能:

const itemReplacer = (array, oldItem, newItem) =>
  array.map(item => item === oldItem ? newItem : item);

回答by Goms

First method

第一种方法

Best way in just one line to replace or update item of array

在一行中替换或更新数组项的最佳方法

array.splice(array.indexOf(valueToReplace), 1, newValue)

Eg:

例如:

let items = ['JS', 'PHP', 'RUBY'];

let replacedItem = items.splice(items.indexOf('RUBY'), 1, 'PYTHON')

console.log(replacedItem) //['RUBY']
console.log(items) //['JS', 'PHP', 'PYTHON']

Second method

第二种方法

An other simple way to do the same operation is :

执行相同操作的另一种简单方法是:

items[items.indexOf(oldValue)] = newValue