简体   繁体   中英

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

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

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

you could also reverse the answer above such as

let test = [true];

console.log(typeof test);

// Output: Object True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM