TypeScript清空数组的4种方法


TypeScript中,假如有以下数组datas,并赋值:

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


我们想清空数组,有以下4种方法。

1、将数组设置为[]值

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

2、设置数组长度为 0

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

3、使用splice()函数

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

4、使用``pop()`函数 ,循环调用,直到数组长度为0

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

猜你喜欢

转载自blog.csdn.net/lizhong2008/article/details/133214857