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

A simple comparison of two methods for clearing array elements in JavaScript_javascript skills

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

The example in this article describes a simple comparison of two methods of clearing array elements in JavaScript. Share it with everyone for your reference. The specific analysis is as follows:

There are many ways to clear arrays in JavaScript:

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

Copy after login

Here are the most commonly used first and second types

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

Copy after login

I hope this article will be helpful to everyone’s JavaScript programming design.

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