JavaScript 清空数组的三种方法


1. 用“length”清除

设置数组的长度length为0 ,则清空数组。

1 var fruits = ["香蕉", "橘子", "苹果", "芒果"];
2 fruits.length = 0;
3 console.log("清除后数组=>", fruits); // 输出值:[]

2. 用splice()清除

splice()是ES6以后新增的方法,用于添加或删除数组中的元素。

1 var fruits = ["香蕉", "橘子", "苹果", "芒果"];
2 fruits.splice(0);
3 console.log("清除后数组=>", fruits); // 输出值:[]

3. 用[]清除

用[],重新定义数组。

1 var fruits = ["香蕉", "橘子", "苹果", "芒果"];
2 fruits = [];
3 console.log("清除后数组=>", fruits); // 输出值:[]

参考网址


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM