简体   繁体   中英

Strange behavior when removing an item from Array in Polymer 1.x

Suppose there's an array called '_arr' from which I remove an item. Before removing though I log it to console. Problem is that log shows the array as if the item is removed already. I have reviewed data system in Polymer Documentation and still scratching my head.

Am I missing something on how data system works or I should be looking somewhere else for the cause?

EDIT: _arr is an array of strings and I am passing an event like:

this.fire('rmv-item' , {item: 'item content which is string'});

Here's the code

_removeItemFromArr: function(e) {

    const index = this._arr.indexOf(e.detail.item) ; 
    console.log('array before remoivng item:' , this._arr , index); //item doesn't exist

    if (index>-1) {  this.splice('_arr' , index, 1  }

    console.log('array after removing item: ' , this._arr , index); //item doesn't exist
},

The problem is that things are doing exactly what you say: the console logs the array , it most emphatically does not log the array "as it was at some specific time in the past", it logs the array as it is when log actually runs. And because the logging operation is not synchronous, by the time it actually writes the crosslinked reference and symbol-table-linked data to the browser console, you already removed the data from the array, so what you see is what console.log sees when it actually kicks in.

If you want a true snapshot of what your array ways "when you call log", don't log the array, log a copy of the array, which is guaranteed to generate synchronously using something like slice() :

const index = this._arr.indexOf(e.detail.item); 
console.log(`array before removing item at [${index}]: ${this._arr.slice()}`);

And job's a good'n.

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