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

This question already has answers here:
How do I empty an array in JavaScript?
(17 answers)
Closed 8 years ago.
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. 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.

Related

Is there a real alternative to "for ... in Object" in Javascript? (For debugging purposes) [duplicate]

This question already has answers here:
List All Prototype Properties of a Javascript Object
(3 answers)
Is it possible to get the non-enumerable inherited property names of an object?
(11 answers)
How to iterate over all properties in object's prototype chain?
(1 answer)
How do I loop through or enumerate a JavaScript object?
(48 answers)
How to console.log all inherited properties?
(4 answers)
Closed 3 months ago.
The community reviewed whether to reopen this question 3 months ago and left it closed:
Original close reason(s) were not resolved
As the MDN website says "for...in is most practically used for debugging purposes", which I also am doing. Is there any other way to get the same results instead of using for ... in to get an array of the keys?
Every other thread on stackoverflow I read about it gave alternatives like in the code below, that are not a solution for getting the same functionality.
var myp= document.createElement('p');
var a = new Array();
for (var each in myp) { a.push(each);}
var b = Object.keys(myp);
var c = Object.getOwnPropertyNames(myp);
console.log(a,b,c);
Edit: The "duplicate" given as closing reason has a totally other question's purpose, and unsurprisingly their isn't an answer to my question on that duplicate thread either. :/
To emulate for..in, you would have to loop through the object's internal prototypes until you reached the top of the prototype chain.
const emulateForIn = (obj) => {
const properties = new Set();
while (obj) {
for (const key of Object.keys(obj)) {
properties.add(key);
}
obj = Object.getPrototypeOf(obj);
}
return [...properties];
}
console.log(emulateForIn(document.createElement('p')));
This probably isn't 100% spec-compliant, but it'll be close enough the vast majority of the time.
That said, both this and your original code is quite odd, as is the recommendation you're quoting in your link - if you're debugging, usually just doing console.log(obj) or console.dir(obj) would be easier so as not to pollute the console with lots and lots of properties (you can expand the object on demand by clicking on it in any modern browser's devtools).

How to let user defined mehods not being iliterated in a for in statement [duplicate]

This question already has answers here:
Why is using "for...in" for array iteration a bad idea?
(28 answers)
How to define method in javascript on Array.prototype and Object.prototype so that it doesn't appear in for in loop
(4 answers)
Closed 1 year ago.
This is the piece code to show my question:
var data=[];
for(var pro in data) {
console.log('Property: '+pro);
}
Array.prototype.Dummy=function() {
};
for(var pro in data) {
console.log('Property:'+pro);
}
I expect the 2 for in statements behave the same, the first prints nothing, reasonable, but the second one will list 'Dummy' only as the array's property, even Array has lots of buildin methods.
The user defined method is different from build in, why?
The reason I ask this question is that I use 3 party libraries, if I extend buildin data types(like Array, Date ect.), I'll potentially modify what their for in statements do.

How to add item to object JS [duplicate]

This question already has answers here:
Is it possible to add dynamically named properties to JavaScript object?
(20 answers)
Closed 2 years ago.
I have looked all over google and i have found nothing that fits my needs. How would you add an item to an object. I basically have a string variable that i want as the key. Therefore i cant use obj.key = 'something';. I sort of want it like:
obj = {'somekey': 'somevalue'};
obj.add('someotherkey': 'someothervalue');
console.log(obj);
by obj.add() i mean someone's solution
and then console says {'somekey': 'somevalue', 'someotherkey': 'someothervalue'}
Does anyone know a way to do this. I don't care at what position it is just whether it is there. By the way i'm using node if that helps. If you have any questions on my code please ask.
Very simple:
obj["somekey"] = "somevalue";
You can also use a variable instead:
let myVariable = "somekey";
obj[myVariable] = "somevalue";
Or you just use normal object notation:
obj.somekey = "somevalue"

Moving element inside an object in javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript Array rotate()
I have a tricky question for you. I have an object who contain different values and I want to change the index of on element so My first element has to become the last or the third or whatever I want. Is that possible in javascript ??
var object = [{0},{1},{2}]
to
var object = [{2},{0},{1}]
This is an example of what I would like to do.
Thanks in advance.
Your from and to example is a little hard to understand the intent, but based on the body of your question asking
My first element has to become the last or the third or whatever I want
Writing a method to swap 2 elements in an array is easy enough:
function swapElements(a, x, y){
var temp = a[x];
a[x] = a[y];
a[y] = temp;
}
Live example: http://jsfiddle.net/pwY9L/
I assume you mean:
var array = [0,1,2];
It doesn’t really matter if the array contains numbers, objects or whatever. If you want to modify this array, there are many ways to do this in javascript andyou can read up about all the Array prototypes here: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array
F.ex, move the last one and place it first:
array.unshift(array.pop());

Correct way to "delete" a property? [duplicate]

This question already has answers here:
How can I unset a JavaScript variable?
(12 answers)
Closed 9 years ago.
With an Array I know you can use the delete keyword to remove items out of the Array. However, delete will not delete a variable.
var b = "some stuff";
delete b;
console.log(b); // "some stuff"
What's the correct way to "free" the memory used by b ? Does doing just b = null; do the trick?
Possible duplicate of this question about unsetting variables in Javascript with some excellent answers. Short answer - null is probably fine.
In Javascript, you cannot really 'free' any memory yourself; all you can do is remove all references to the memory that an object uses, and the JS engine's garbage collector will recover it. Setting the variable / property to null would be a good starting point.
As regards the use of 'delete', I haven't found a better resource for understanding it than http://perfectionkills.com/understanding-delete/.

Categories