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

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

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

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


当前回答

javascript中替换数组元素的函数式方法:

Const replace = (array, index,…items) =>[…数组。Slice (0, index),…项目,…数组。Slice (index + 1)];

其他回答

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

例如:

items[0] = 5;
items[5] = 100;
var index = items.indexOf(3452);

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

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

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

如果你喜欢简洁的JavaScript,想缩短-1的比较,你也可以使用~操作符:

var index = items.indexOf(3452);

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

有时我甚至喜欢写一个包含函数来抽象这个检查,使它更容易理解发生了什么。令人惊叹的是,这对数组和字符串都有效:

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

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

从字符串的ES6/ES2015开始,到数组的ES2016建议,你可以更容易地确定一个源是否包含另一个值:

if (haystack.includes(needle)) {
    // do your thing
}
var index = Array.indexOf(Array value);
        if (index > -1) {
          Array.splice(index, 1);
        }

从这里,您可以根据相同的索引从数组中删除特定的值 你可以在数组中插入值。

 Array.splice(index, 0, Array value);

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]