有没有方法清空数组,如果有可能,可以使用.remove()?
例如,
A = [1,2,3,4];
我怎么才能把它清空?
有没有方法清空数组,如果有可能,可以使用.remove()?
例如,
A = [1,2,3,4];
我怎么才能把它清空?
当前回答
关于这段时间,有很多困惑和错误信息;回答和评论中的pop/shift表现。while/pop解决方案的性能(如预期)最差。实际情况是,对于在循环中运行代码段的每个示例,安装程序只运行一次。如:
var arr = [];
for (var i = 0; i < 100; i++) {
arr.push(Math.random());
}
for (var j = 0; j < 1000; j++) {
while (arr.length > 0) {
arr.pop(); // this executes 100 times, not 100000
}
}
我创建了一个工作正常的新测试:
http://jsperf.com/empty-javascript-array-redux
警告:即使在这个版本的测试中,您也看不到真正的差异,因为克隆阵列占用了大部分测试时间。它仍然表明拼接是清除阵列的最快方式(不考虑[],因为虽然它是最快的,但实际上并没有清除现有阵列)。
其他回答
要清空数组的当前内存位置,请使用:“myArray.length=0”或“myArray.cop()UN,直到其长度为0”
length:可以将length属性设置为随时截断数组。通过更改数组的长度属性来扩展数组时,实际元素的数量会增加。pop():pop方法从数组中移除最后一个元素,并返回移除的值。shift():shift方法移除第0个索引处的元素,并向下移动连续索引处的值,然后返回移除的值。
例子:
var arr = ['77'];
arr.length = 20;
console.log("Increasing : ", arr); // (20) ["77", empty × 19]
arr.length = 12;
console.log("Truncating : ", arr); // (12) ["77", empty × 11]
var mainArr = new Array();
mainArr = ['1', '2', '3', '4'];
var refArr = mainArr;
console.log('Current', mainArr, 'Refered', refArr);
refArr.length = 3;
console.log('Length: ~ Current', mainArr, 'Refered', refArr);
mainArr.push('0');
console.log('Push to the End of Current Array Memory Location \n~ Current', mainArr, 'Refered', refArr);
mainArr.poptill_length(0);
console.log('Empty Array \n~ Current', mainArr, 'Refered', refArr);
Array.prototype.poptill_length = function (e) {
while (this.length) {
if( this.length == e ) break;
console.log('removed last element:', this.pop());
}
};
new Array()|[]使用Array构造函数或数组文字创建具有新内存位置的Array。mainArr=[];//新的空数组被寻址到mainArr。var arr=新数组(“10”);//数组构造函数arr.unshift('1');//添加到前面arr.push('15');//添加到末尾console.log(“添加后:”,arr);//["1", "10", "15"]arr.pop();//从末端移除arr.shift();//从前面拆下console.log(“删除后:”,arr);//["10"]var arrLit=['14','17'];console.log(“array literal«”,indexedItem(arrLit));//{0,14}{1,17}函数索引项{var indexedStr=“”;arr.forEach(函数(项、索引、数组){indexedStr+=“{”+index+“,”+item+“}”;console.log(项,索引);});返回indexedStr;}slice():通过使用slice函数,我们从原始数组中获得一个元素的浅拷贝,带有新的内存地址,这样对clonerr的任何修改都不会影响到实际的|原始数组。var浅拷贝=mainArr.slice();//这是如何复制的var cloneArr=mainArr.切片(0,3);console.log('Main',mainArr,'\tCloned',cloneArr);克隆错误长度=0;//清除阵列的当前内存位置。console.log('Main',mainArr,'\tCloned',cloneArr);
这里是保持相同数组(“可变”)的最快工作实现:
function clearArray(array) {
while (array.length > 0) {
array.pop();
}
}
仅供参考,它不能简化为while(array.pop()):测试将失败。
仅供参考,Map和Set定义clear(),Array也可以使用clear(()。
TypeScript版本:
function clearArray<T>(array: T[]) {
while (array.length > 0) {
array.pop();
}
}
相应的测试:
describe('clearArray()', () => {
test('clear regular array', () => {
const array = [1, 2, 3, 4, 5];
clearArray(array);
expect(array.length).toEqual(0);
expect(array[0]).toEqual(undefined);
expect(array[4]).toEqual(undefined);
});
test('clear array that contains undefined and null', () => {
const array = [1, undefined, 3, null, 5];
clearArray(array);
expect(array.length).toEqual(0);
expect(array[0]).toEqual(undefined);
expect(array[4]).toEqual(undefined);
});
});
这里是更新的jsPerf:http://jsperf.com/array-destroy/32 http://jsperf.com/array-destroy/152
jsPerf脱机。类似基准:https://jsben.ch/hyj65
如果您对内存分配感兴趣,可以使用jsfiddle这样的东西与chrome开发工具的时间线选项卡来比较每种方法。您将希望在“清除”阵列后使用底部的垃圾箱图标强制垃圾收集。这将为您选择的浏览器提供更明确的答案。这里的很多答案都是旧的,我不会依赖它们,而是像上面@tanguy_k的答案那样进行测试。
(有关上述选项卡的介绍,您可以在此处查看)
Stackoverflow迫使我复制jsfiddle,所以这里是:
<html>
<script>
var size = 1000*100
window.onload = function() {
document.getElementById("quantifier").value = size
}
function scaffold()
{
console.log("processing Scaffold...");
a = new Array
}
function start()
{
size = document.getElementById("quantifier").value
console.log("Starting... quantifier is " + size);
console.log("starting test")
for (i=0; i<size; i++){
a[i]="something"
}
console.log("done...")
}
function tearDown()
{
console.log("processing teardown");
a.length=0
}
</script>
<body>
<span style="color:green;">Quantifier:</span>
<input id="quantifier" style="color:green;" type="text"></input>
<button onclick="scaffold()">Scaffold</button>
<button onclick="start()">Start</button>
<button onclick="tearDown()">Clean</button>
<br/>
</body>
</html>
您应该注意,这可能取决于数组元素的类型,因为javascript管理字符串的方式不同于其他基本类型,更不用说对象数组了。类型可能会影响发生的情况。
使用拼接方法清空数组A的内容是一种更易于跨浏览器且更优化的解决方案,如下所示:
A.拼接(0,A.长度);
如果您使用常量,则您别无选择:
const numbers = [1, 2, 3]
您不能重新设计:
numbers = []
您只能截断:
numbers.length = 0