【问题标题】:How to replace or update item of array in JavaScript如何在 JavaScript 中替换或更新数组项
【发布时间】:2018-06-16 05:10:06
【问题描述】:

标题描述了我想要的,这是代码

如果我们将产品添加到items,如果它不存在(id 不同),一切都很好。但如果它存在,我只想修改该项目。区别在于items 数组中每个项目的 id。

Eg : if first, id = 1, qty = 3, and next, id = 1, qty = 3, 我想更新items中的qty

new Vue({
  el: '#fact',
  data: {
    input: {
      id: null,
      qty: 1
    },
    items: []
  },
  methods: {
    addItem() {
      var item = {
        id: this.input.id,
        qty: this.input.qty
      };
      
      if(index = this.itemExists(item) !== false)
      {
          this.items.slice(index, 1, item);
          return null;
      }
      
      this.items.push(item)
    },
    itemExists($input){
       for (var i = 0, c = this.items.length; i < c; i++) {
           if (this.items[i].id == $input.id) {
               return i;
          }
       }
       return false;
    }
  }
})
<Doctype html>
  <html>

  <head>
    <meta charset="utf-8" />
    <title>Add product</title>
  </head>

  <body>
    <div id="fact">
      <p>
        <input type="text" v-model="input.id" placeholder="id of product" />
      </p>
      <p>
        <input type="text" v-model="input.qty" placeholder="quantity of product" />
      </p>
      <button @click="addItem">Add</button>

      <ul v-if="items.length > 0">
        <li v-for="item in items">{{ item.qty + ' ' + item.id }}</li>
      </ul>
      
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
  </body>

  </html>

【问题讨论】:

    标签: javascript arrays vue.js vuejs2


    【解决方案1】:
    if(index = this.itemExists(item) !== false)
    {
        for (let value of this.items) {
            if(value.id === item.id) {
                value.qty = item.qty;
            }
         }
    
         return null;
     }
    

    【讨论】:

    • 差异是由项目的 id (item.id) 决定的,你认为它真的对我有帮助吗?
    • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因
    【解决方案2】:

    你可能误用了slice 方法,change slice to splice 对我有用:

    this.items.splice(index, 1, item)
    

    slice 不会根据documentation here 触发视图更新。

    Vue 包装了观察到的数组的变异方法,因此它们也将 触发视图更新。包装的方法是:

    • 推()
    • pop()
    • shift()
    • unshift()
    • 拼接()
    • 排序()
    • 反向()

    【讨论】:

    • 感谢您的评论!但即使是修改,他这次也添加了有问题的项目。通过缺点,我希望 items 中已经添加的 item 被更改!
    • 通过使用splice(index, 1, item),您可以将原始项目替换为新项目。如果您有其他字段,您可以使用 Object.assign 创建一个合并到原始项目中的新项目,然后替换它。比如:splice(index, 1, Object.assign({}, this.items[index], item)).
    • 直接在原地修改项目不是一个好主意,因为 Vue 无法检测到您所做的更改。见Caveates
    • 感谢您的帮助!片刻之后检查它不起作用,我发现if(index = this.itemExists(item) !== false) 那将是(index = this.itemExists(item)) !== false)。使用相同的代码,当然包括您的评论(splice instand of slice),现在一切正常!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-14
    • 1970-01-01
    • 2021-09-29
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多