js如何将数组中的元素清空

js如何将数组中的元素清空:
删除数组中所有的元素的方法有多种,下面就简单扼列举几种。
方法一:

var theArray=["蚂蚁部落","青岛市南区",2];
console.log(theArray.length);
theArray.splice(0,theArray.length);
console.log(theArray.length);

 使用splice()函数可以删除数组中所有的元素。

关于splice()函数可以参阅JavaScript的Array对象的splice()方法一章节。
方法二:

var theArray=["蚂蚁部落","青岛市南区",2];
console.log(theArray.length);
theArray.length=0;
console.log(theArray.length);

 将数组的length属性值设置为0即可将数组清空。

方法三:

var theArray=["蚂蚁部落","青岛市南区",2];
var beifen=theArray;
console.log(theArray.length);
theArray=[];
console.log(theArray.length);
console.log(beifen.length);

 此方法其实不算是删除数组中的元素,只是将原数组的引用重新指向一个空数组而已。

原文地址是:http://www.softwhy.com/forum.php?mod=viewthread&tid=9345

更多内容可以参阅:http://www.softwhy.com/javascript/

猜你喜欢

转载自softwhy.iteye.com/blog/2269325