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

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

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

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


当前回答

如果使用一个复杂的对象(甚至是一个简单的对象),你可以使用es6, Array.prototype.findIndex是一个很好的选择。对于OP的数组,他们可以这样做,

const index = items.findIndex(x => x === 3452)
items[index] = 1010

对于更复杂的对象,这真的很管用。例如,

const index = 
    items.findIndex(
       x => x.jerseyNumber === 9 && x.school === 'Ohio State'
    )

items[index].lastName = 'Utah'
items[index].firstName = 'Johnny'

其他回答

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的更多信息

用for循环很容易完成。

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

这个就行了

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()属性。

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循环解决了这个问题,遍历原始数组,并将匹配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;
};