用JavaScript清空数组

Emptying an array is a common JavaScript task but too often I see the task performed in the incorrect way.  Many times developers will create a new array:

清空数组是常见JavaScript任务,但是我经常看到任务以错误的方式执行。 开发人员很多时候会创建一个新的数组:


myArray = []; // bad


That isn't the optimal way to get a fresh array;  to truncate an array, and thus empty it, you should set the length property to zero:

这不是获得新阵列的最佳方法。 要截断数组并因此清空它,应将length属性设置为零:


myArray.length = 0; // good!


Setting the length equal to zero empties the existing array, not creating another array! This helps you to avoid pointer issues with arrays as well. With the new array method above:

将长度设置为零将清空现有数组,而不创建另一个数组! 这也可以帮助您避免数组出现指针问题。 使用上面的新数组方法:


// ... as provided by Dag in the comments
A = [1,2,3,4,5]
B = A
A = []
console.log(B) // [1,2,3,4,5]


The length truncation would make both A and B the original array but empty!

length截断会使AB成为原始数组,但为空!

翻译自: https://davidwalsh.name/empty-array

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值