How to replace an item in an array with JavaScript?

后端 未结 26 2166
执笔经年
执笔经年 2020-11-29 15:33

Each item of this array is some number.

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

How do I replace some number in with array with a new on

相关标签:
26条回答
  • 2020-11-29 16:11

    The immutable way to replace the element in the list using ES6 spread operators and .slice method.

    const arr = ['fir', 'next', 'third'], item = 'next'
    
    const nextArr = [
      ...arr.slice(0, arr.indexOf(item)), 
      'second',
      ...arr.slice(arr.indexOf(item) + 1)
    ]
    

    Verify that works

    console.log(arr)     // [ 'fir', 'next', 'third' ]
    console.log(nextArr) // ['fir', 'second', 'third']
    
    0 讨论(0)
  • 2020-11-29 16:11
    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.
    
    0 讨论(0)
提交回复
热议问题