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

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

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

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


当前回答

 items[items.indexOf(3452)] = 1010

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

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

其他回答

这个就行了

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循环解决了这个问题,遍历原始数组,并将匹配arreas的位置添加到另一个数组,然后遍历该数组,并在原始数组中更改它,然后返回它,我使用了一个箭头函数,但一个常规函数也可以工作。

var replace = (arr, replaceThis, WithThis) => {
    if (!Array.isArray(arr)) throw new RangeError("Error");
    var itemSpots = [];
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == replaceThis) itemSpots.push(i);
    }

    for (var i = 0; i < itemSpots.length; i++) {
        arr[itemSpots[i]] = WithThis;
    }

    return arr;
};

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

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

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

如果你知道它的价值,

items[items.indexOf(334)] = 1010;

如果你想知道这个值是否存在,那么使用,

var point = items.indexOf(334);

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

如果你知道地点(位置),那么直接使用,

items[--position] = 1010;

如果你想替换一些元素,你知道起始位置只意味着,

items.splice(2, 1, 1010, 1220);

有关.splice的更多信息

 items[items.indexOf(3452)] = 1010

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

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