Skip to content

Commit 2cd715c

Browse files
committed
update
1 parent 02f85a9 commit 2cd715c

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

README.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,31 @@
1919
* <a href="#0107">2016-01-07:往数组中插入一个元素</a>
2020

2121

22+
####<a id="0122">2016-01-22: 清空一个数组</a>
23+
24+
清空数组通常的做法是直接使用`arr = []`的方式。不过这里想介绍另一种方式:使用`属性length`
25+
26+
var a = [1,2,3];
27+
a.length = 0;
28+
console.log(a); // []
29+
30+
其实我在**2016-01-07:往数组中插入一个元素**就提到过,JS中直接操作数组的`length`属性,会影响到数组具体的内容。这里我们再来看看这两种清空数组的方式 有什么不同。
31+
32+
var a = [1,2,3];
33+
var b = a;
34+
a = [];
35+
console.log(a); // []
36+
console.log(b); // [1,2,3]
37+
38+
var c = [1,2,3,4];
39+
var d = c;
40+
c.length = 0;
41+
console.log(c); // []
42+
console.log(d); // []
43+
44+
使用**将属性length设置为零**的方式会把从原数组复制的数组也清空,而使用`arr = []`的方式则不会。
45+
46+
2247

2348
####<a id="0121">2016-01-21:链式调用对象实例的方法</a>
2449

0 commit comments

Comments
 (0)