Home > Web Front-end > JS Tutorial > body text

JavaScript清空数组元素的两种方法简单比较_javascript技巧

WBOY
Release: 2016-05-16 15:50:33
Original
1332 people have browsed it

本文实例讲述了JavaScript清空数组元素的两种方法简单比较。分享给大家供大家参考。具体分析如下:

JavaScript中数组清空有多种方法:

var arr = [1, 2, 3]; 
arr = [];//方法一
arr.length = 0;//方法二
arr = null;//方法三
delete arr;//方法四

Copy after login

这里比较最常用的第一种和第二种

var arr = [1, 2, 3];
// 方法一
// 优点:如果有其他地方用到了数组arr中的元素,这种方法相对来说更安全。并且也简单快捷
// 缺点:增加了额外的内存开销,重新开辟了一个新的空数组
arr = [];
// 方法二
// 优点:如果其他用到arr元素的地方想同步观察到arr元素被清空的效果,那么用这个是较好的选择
// 缺点:设置数组的length属性后,会导致数组删除index为length及其之后的元素,这样性能开销很大
// 这种方法也是四种方法中性能最差的。
arr.length = 0;

Copy after login

希望本文所述对大家的javascript程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!