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
4 Answers
Reset to default 14You 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
版权声明:本文标题:Javascript - Array with Boolean Keys? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738577130a2100943.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论