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

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

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

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


当前回答

第一个方法

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

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']

第二种方法

另一种简单的方法是:

items[items.indexOf(oldValue)] = newValue

其他回答

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);

第一个方法

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

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']

第二种方法

另一种简单的方法是:

items[items.indexOf(oldValue)] = newValue
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项= [523,3452,334,31,5346] var替换= (arr, oldVal, newVal) => (arr[arr.indexOf(oldVal)] = newVal, arr) 控制台。日志(替换项,3452,1010)