开发者

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

开发者 https://www.devze.com 2023-01-22 12:06 出处:网络
This question already has answers here: How do I empty an array in JavaScript? (18 answers) Closed 8 years ago.
This question already has answers here: How do I empty an array in JavaScript? (18 answers) Closed 8 years ago.

I'm trying to empty an array containing my drawn开发者_JAVA技巧 coordinates when a button "clear" is pressed.

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


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


drawnDivs = [];


It was answered in Stack Overflow question How do I empty an array in 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 up on these two methods by Dr. Axel Rauschmayer.


An optimized way to do it is:

while (arr.pop()) {}

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消