admin管理员组

文章数量:1201373

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

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
Share Improve this question asked Jan 24, 2013 at 4:30 user1846065user1846065
Add a comment  | 

4 Answers 4

Reset to default 14

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.

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"}

you could also reverse the answer above such as

let test = [true];

console.log(typeof test);

// Output: Object True

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";

本文标签: JavascriptArray with Boolean KeysStack Overflow