On the problem of JS array

a: AA[];
b: AA;

ngOnInit() {
    this.a = [];
}

x() {
    this.a = [...this.a, this.b];  <--- ?
}
May.20,2022

clipboard.png

I hope I can help the subject!


first take a look at the parsed results of babel

 this.a = [...this.a, this.b];
          
 this.a = [].concat(_toConsumableArray(this.a), [this.b]);
from this function we can see that if a new array clone is created for an array, otherwise the Array.from method will be called to create a new array instance from a similar array or iterable object
function _toConsumableArray(arr) {
 if (Array.isArray(arr)) { 
    for (var i = 0, arr2 = Array(arr.length); i < arr.length; iPP) {
      arr2[i] = arr[i]; } return arr2; 
    } else { 
      return Array.from(arr); 
    }
  }

Let's try it again

 [...'test',10];   // ['t','e','s','t',10] 

 //
 this.a = [...this.a, this.b];
  this.a  ->  =>  this.a  [].concat()    this.b 

es6


... unfold operator | MDN

you can go in and have a look at specific examples.

Menu