user1846065
user1846065

Reputation:

Javascript - Array with Boolean Keys?

I'm relatively new to Javascript, and there's probably just a trick I'm not familiar with, but how can I assign boolean values 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 to happen:

var test = new Array();

//Some stuff

Object.keys(test); // Yield [ "false" , false ]
Object.keys(test).length; // Yield 2

Upvotes: 9

Views: 16211

Answers (4)

Josh
Josh

Reputation: 1267

you could also reverse the answer above such as

let test = [true];

console.log(typeof test);

// Output: Object True

Upvotes: 2

Andrew Whitaker
Andrew Whitaker

Reputation: 126052

You can't use arbitrary indexes in an array, but you can use an object literal to (sort of) accomplish what you're 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 boolean primitive will just end up in creating an object property named 'false'.

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

This is why your first example's Object.keys().length call returns just 1.

For an excellent getting started guide on objects in JavaScript, I would recommend MDN's Working with objects.

Upvotes: 14

arbales
arbales

Reputation: 5536

Arrays in Javascript aren't associative, so you cannot assign values to keys in them.

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

You're interested in an Object!

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

Upvotes: 2

Raekye
Raekye

Reputation: 5131

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

Upvotes: 1

Related Questions