---
title: "JavaScript中清空数组的三种方式"
author: "zhouyrt"
date: "2011-01-24T16:31:11Z"
tags: []
categories: ["Web前端"]
slug: "javascript"
draft: false
lastmod: "2011-04-05T08:21:31Z"
id: 893955
url: "https://snandy.iteye.com/blog/893955"
---

**方式1，splice**

 

```
var ary = [1,2,3,4];
ary.splice(0,ary.length);
console.log(ary); // 输出 []，空数组，即被清空了
```

 

**方式2，length赋值为0**

这种方式很有意思，其它语言如Java，其数组的length是只读的，不能被赋值。如

```
int[] ary = {1,2,3,4};
ary.length = 0;
```

 

Java中会报错，编译通不过。

而JS中则可以，且将数组清空了，如

```
var ary = [1,2,3,4];
ary.length = 0;
console.log(ary); // 输出 []，空数组，即被清空了
```

 

目前 Prototype中数组的 [clear](http://api.prototypejs.org/language/Array/prototype/clear/) 方法和mootools库中数组的 [empty](http://mootools.net/docs/core/Types/Array#Array:empty) 方法使用这种方式清空数组。

**方式3，赋值为\[]**

 

```
var ary = [1,2,3,4];
ary = []; // 赋值为一个空数组以达到清空原数组
```

 

Ext库Ext.CompositeElementLite类的 [clear](http://www.sencha.com/products/core/docs/source/CompositeElementLite.html#method-Ext.CompositeElementLite-clear) 方法使用这种方式清空。

 

方式2 保留了数组其它属性，方式3 则未保留。

 

很多人认为方式2的效率很高些，因为仅仅是给length重新赋值了，而方式3则重新建立个对象。经 测试 恰恰是方式3的效率高。测试代码：

 

```
var a = [];
for (var i=0; i< 1000000; i++){
	a.push(i);
}
var start = new Date();
//a = [];
a.length = 0;
var end = new Date();
alert(end - start);
```

 

测试结果：

IE6 IE7 IE8 IE9 Firefox Safari Chrome a.length=0 94 29 14 1 4 3 1 a=\[] 0 0 0 0 0 0 0

 

 

以上结果可看到:方式3更快，效率更高。

 

 

从测试结果上看如果不保留原数组的其它属性Ext采用的方式更值得推荐。