4 ways to clear arrays in TypeScript


In TypeScript, if there is the following array datas and assignment:

let datas:Array<ItemData> = new Array<ItemData>();
for(let i=0;i<100;i++){
  let item:ItemData = new ItemData()
  datas[i] =item;
}


We want to clear the array, there are the following 4 methods.

1. Set the array to [] value

datas=[];
console.log(datas.length); // 0

2. Set the array length to 0

datas.length=0;
console.log(datas.length); // 0

3. Use splice()functions

datas.splice(0, datas.length);
console.log(datas.length); // 0

4. Use the ``pop()` function and call it in a loop until the array length is 0

 while(datas.length>0) {
    datas.pop()
 }
 
console.log(datas.length); // 0

Guess you like

Origin blog.csdn.net/lizhong2008/article/details/133214857