简体   繁体   中英

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

I am using VueJS to display a list of groceries. 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. 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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