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

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

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

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


当前回答

下面是一个可重用函数的基本答案:

function arrayFindReplace(array, findValue, replaceValue){
    while(array.indexOf(findValue) !== -1){
        let index = array.indexOf(findValue);
        array[index] = replaceValue;
    }
}

其他回答

 items[items.indexOf(3452)] = 1010

非常适合简单的交换。试试下面的代码片段

const items =数组(523,3452,334,331,5346); console.log(物品) items[items. indexof (3452)] = 1010 console.log(物品)

最简单的方法是使用一些库,如下划线和映射方法。

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

_.map(items, function(num) {
  return (num == 3452) ? 1010 : num; 
});
=> [523, 1010, 334, 31, ...5346]

首先,像这样重写数组:

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

接下来,通过索引号访问数组中的元素。确定索引号的公式为:n-1

要替换数组中的第一项(n=1),写:

items[0] = Enter Your New Number;

在您的示例中,数字3452位于第二个位置(n=2)。所以确定索引号的公式是2-1 = 1。因此,编写下面的代码将3452替换为1010:

items[1] = 1010;

使用indexOf查找元素。

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

如果有人对如何从数组的下标替换一个对象感兴趣,这里有一个解决方案。

通过id查找对象的索引:

const index = items.map(item => item.id).indexOf(objectId)

使用object .assign()方法替换该对象:

Object.assign(items[index], newValue)