Array with boolean keys?

I'm relatively new to Javascript, and probably just a trick I'm not familiar with, but how can I assign booleans to Array keys?

What's happening:

var test = new Array(); test[false] = "asdf"; test['false'] = "fdsa"; Object.keys(test); // Yield [ "false" ] Object.keys(test).length; // Yield 1 

What I want:

 var test = new Array(); //Some stuff Object.keys(test); // Yield [ "false" , false ] Object.keys(test).length; // Yield 2 
+4
source share
3 answers

You cannot use arbitrary indexes in an array, but you can use an object literal to (sort) the execution of what you are after:

 var test = {}; test[false] = "asdf"; test['false'] = "fdsa"; 

However, it should be noted that object properties must be strings (or types that can be converted to strings). Using a logical primitive will simply end up creating an object property called 'false' .

 test[false] === test['false'] === test.false 

This is why your first example Object.keys().length only calls 1 .

For an excellent guide to getting started with objects in JavaScript, I would recommend MDN Working with Objects .

+6
source

Arrays in Javascript are not associative, so you cannot assign values ​​to them.

 var test = []; test.push(true); // [true] test.push(false); // [true, false] 

You are interested in the object!

 var test = {}; test[true] = "Success!"; test[false] = "Sadness"; // {'false': "Sadness", 'true': "Success"} 
+2
source

Javascript arrays are based only on a numerical index. You can use 0 and 1 as keys (although I can't think of a case where you need logical keys). myArr[0] = "mapped from false"; myArr[1] = "mapped from true";

+1
source

All Articles