JavaScript 的 array.clear() 不是函数吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4020548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:09:56  来源:igfitidea点击:

Is JavaScript's array.clear() not a function?

javascriptarraysclear

提问by Nona Urbiz

I'm trying to empty an array containing my drawn coordinates when a button "clear" is pressed.

当按下“清除”按钮时,我试图清空一个包含我绘制坐标的数组。

When I call drawnDivs.clear(), I get an error that it is not a function. drawnDivsis certainly an array, and I have Firebugconsole.logs printing things out. It's hosted here.

当我调用 时drawnDivs.clear(),我收到一个错误,指出它不是一个函数。drawnDivs肯定是一个数组,我有Firebugconsole.log打印出来的东西。它在这里托管

回答by jordanbtucker

Nope, it's not. But drawnDivs.length = 0should work.

不,不是。但drawnDivs.length = 0应该工作。

回答by Mike Ruhlin

drawnDivs = [];

绘制的Divs = [];

回答by subhaze

It was answered in Stack Overflow question How do I empty an array in JavaScript?.

在 Stack Overflow 问题中回答了如何在 JavaScript 中清空数组?.

Two examples from the answer:

答案中的两个例子:

var A = ['some', 'values', 'here'];

//Method 1

//(This was my original answer to the question)

A = [];




// Method 2 (as suggested by Matthew Crumley)

A.length = 0

And here is a nice write upon these two methods by Dr. Axel Rauschmayer.

这里是一个很好的写了这两种方法属于Axel Rauschmayer先生博士。

回答by user3271659

An optimized way to do it is:

一个优化的方法是:

while (arr.pop()) {}

See http://jsperf.com/kbk-clear-array/2.

请参阅http://jsperf.com/kbk-clear-array/2

回答by Debosmit Ray

You could alternately use the Prototype library and then, use Prototype's clear()method.

您可以交替使用 Prototype 库,然后使用 Prototype 的clear()方法。