数组中的每一项都是一个数字:

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

如何用新物品替换旧物品?

例如,我们想用1010替换3452,该怎么做呢?


当前回答

这个就行了

Array.prototype.replace = function(a, b) {
    return this.map(item => item == a ? b : item)
}

用法:

let items = ['hi', 'hi', 'hello', 'hi', 'hello', 'hello', 'hi']
console.log(items.replace('hello', 'hi'))

输出:

['hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi']

好处是,每个数组都有.replace()属性。

其他回答

用for循环很容易完成。

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

const items =数组(1,2,3,4,5); console.log(物品) items[items. indexof (2)] = 1010 console.log(物品)

ES6道:

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

我们想用1010替换3452,解决方案:

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

当然,这个问题是很多年前的问题了,现在我更喜欢使用不可变的解决方案,当然,这对ReactJS来说是很棒的。

为了经常使用,我提供以下功能:

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

最简单的方法是这样。

var items = Array(523,3452,334,31, 5346);
var replaceWhat = 3452, replaceWith = 1010;
if ( ( i = items.indexOf(replaceWhat) ) >=0 ) items.splice(i, 1, replaceWith);

console.log(items);
>>> (5) [523, 1010, 334, 31, 5346]

如果你想要一个简单的糖纸,你可以:

(elements = elements.filter(element => element.id !== updatedElement.id)).push(updatedElement);

如:

let elements = [ { id: 1, name: 'element one' }, { id: 2, name: 'element two'} ];
const updatedElement = { id: 1, name: 'updated element one' };

如果你没有id,你可以像这样字符串化元素:

(elements = elements.filter(element => JSON.stringify(element) !== JSON.stringify(updatedElement))).push(updatedElement);