简体   繁体   English

当我将数组索引存储为变量时,代码不起作用

[英]Code doesn’t work when I store an array index as a variable

I am using VueJS to display a list of groceries. 我正在使用VueJS显示杂货清单。 Each grocery item can be incremented or decremented. 每个杂货项目都可以递增或递减。 I wrote the following function to decrement: 我写了以下函数递减:

deleteItem: function(index) {
  this.items[index].quantity -= 1;
  if (this.items[index].quantity < 0) {
    this.items[index].quantity = 0;
  };
}

I'm trying to make my code more DRY so I tried putting this.items[index].quantity in a variable. 我试图使代码更干燥,因此尝试将this.items[index].quantity放入变量中。 I was wondering why my code doesn't work whenI do this: 我想知道为什么当我这样做时我的代码不起作用:

deleteItem: function(index) {
  var itemQuantity = this.items[index].quantity
  itemQuantity -= 1;
  if (this.items[index].quantity < 0) {
    this.items[index].quantity = 0;
  };
}

The problem is you're modifying a value instead of a reference . 问题是您正在修改而不是引用

Value types, such as numbers and booleans, are always copied. 值类型(例如数字和布尔值)始终被复制。 This means you lose the reference to where that value came from. 这意味着您将失去对价值来源的参考。

Example: 例:

 var obj = { a: 1 }; var a = obj.a; a += 1; console.log(a); // changed console.log(obj.a); // unchanged 

What you could do instead is hold a reference to the object you're interested in since objects are always a reference. 你可以做的反而是坚持你有兴趣,因为对象总是一个参考的对象的引用。

 var items = [ { quantity: 0 }, ]; var item = items[0]; console.log('Initial state:', item.quantity); item.quantity -= 1; console.log('After the change:', item.quantity); if (item.quantity < 0) { item.quantity = 0; console.log('After the correction:', item.quantity); } 

You can pass directly the item instead of index : 您可以直接传递项目而不是索引:

 new Vue({ el: "#app", data: function() { return { items: [ { name: 'Product 1', quantity: 15 }, { name: 'Product 2', quantity: 2 }, { name: 'Product 3', quantity: 12 } ] } }, methods: { addQuantity: function( item, quantityToAdd ) { if( item.quantity + quantityToAdd < 0 ){ item.quantity = 0; } else { item.quantity += quantityToAdd; } }, increment: function( item ) { this.addQuantity( item, 1 ); }, decrement: function( item ) { this.addQuantity( item, -1 ); } } }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.5/vue.js"></script> <div id="app"> <div v-for="item in items" :key="item"> {{ item.name }} {{ item.quantity }} <button @click="decrement(item)" type="button">Decrement</button> <button @click="increment(item)" type="button">Increment</button> </div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM