有没有方法清空数组,如果有可能,可以使用.remove()?

例如,

A = [1,2,3,4];

我怎么才能把它清空?


当前回答

您可以将其添加到JavaScript文件中,以允许“清除”数组:

Array.prototype.clear = function() {
    this.splice(0, this.length);
};

然后可以这样使用:

var list = [1, 2, 3];
list.clear();

或者,如果你想确保你没有破坏一些东西:

if (!Array.prototype.clear) {
    Array.prototype.clear = function() {
       this.splice(0, this.length);
    };
}

很多人认为不应该修改本机对象(如Array),我倾向于同意。在决定如何处理这件事时请谨慎。

其他回答

您可以将其添加到JavaScript文件中,以允许“清除”数组:

Array.prototype.clear = function() {
    this.splice(0, this.length);
};

然后可以这样使用:

var list = [1, 2, 3];
list.clear();

或者,如果你想确保你没有破坏一些东西:

if (!Array.prototype.clear) {
    Array.prototype.clear = function() {
       this.splice(0, this.length);
    };
}

很多人认为不应该修改本机对象(如Array),我倾向于同意。在决定如何处理这件事时请谨慎。

我很惊讶还没有人提出这一点:

let xs = [1,2,3,4];
for (let i in xs)
    delete xs[i];

这会产生一个与其他解决方案截然不同的数组。从某种意义上说,数组已被“清空”:

xs
=> Array [ <4 empty slots> ]

[...xs]
=> Array [ undefined, undefined, undefined, undefined ]

xs.length
=> 4

xs[0]
=> ReferenceError: reference to undefined property xs[0]

可以使用[,,,]或array(4)生成等效的数组

如果您使用常量,则您别无选择:

const numbers = [1, 2, 3]

您不能重新设计:

numbers = []

您只能截断:

numbers.length = 0

使用拼接方法清空数组A的内容是一种更易于跨浏览器且更优化的解决方案,如下所示:

A.拼接(0,A.长度);

性能测试:

http://jsperf.com/array-clear-methods/3

a = []; // 37% slower
a.length = 0; // 89% slower
a.splice(0, a.length)  // 97% slower
while (a.length > 0) {
    a.pop();
} // Fastest