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

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

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

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


当前回答

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

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

通过id查找对象的索引:

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

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

Object.assign(items[index], newValue)

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

function arrayFindReplace(array, findValue, replaceValue){
    while(array.indexOf(findValue) !== -1){
        let index = array.indexOf(findValue);
        array[index] = replaceValue;
    }
}
presentPrompt(id,productqty) {
    let alert = this.forgotCtrl.create({
      title: 'Test',
      inputs: [
        {
          name: 'pickqty',
          placeholder: 'pick quantity'
        },
        {
          name: 'state',
          value: 'verified',
          disabled:true,
          placeholder: 'state',

        }
      ],
      buttons: [
        {
          text: 'Ok',
          role: 'cancel',
          handler: data => {

            console.log('dataaaaname',data.pickqty);
            console.log('dataaaapwd',data.state);


          for (var i = 0; i < this.cottonLists.length; i++){

            if (this.cottonLists[i].id == id){
                this.cottonLists[i].real_stock = data.pickqty;

            }
          }

          for (var i = 0; i < this.cottonLists.length; i++){

            if (this.cottonLists[i].id == id){
              this.cottonLists[i].state = 'verified';   

          }
        }
            //Log object to console again.
            console.log("After update: ", this.cottonLists)
            console.log('Ok clicked');
          }
        },

      ]
    });
    alert.present();
  }

As per your requirement you can change fields and array names.
thats all. Enjoy your coding.

用for循环很容易完成。

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