Can I use a string as the key in a JavaScript object?
var method,
obj;
method = function () {
return "foo";
};
// works
obj = {
'foo': 'bar'
};
// does not work
obj = {
method(): 'bar'
};
Can I use a string as the key in a JavaScript object?
var method,
obj;
method = function () {
return "foo";
};
// works
obj = {
'foo': 'bar'
};
// does not work
obj = {
method(): 'bar'
};
You can use square bracket syntax in javascript. This cannot be done when declaring an object literal though. You will have to do something like the following.
obj = {};
obj[method()] = "bar";
if you create an empty object first, then call the method as if it was the key, it will assign it how you want it to.
var method = function() {
return 'bar';
};
var obj = {};
obj[method()] = 'bar';
Not that way.
You CAN do this:
function doStuff() {
return "foo";
};
var obj = {}
;
obj[doStuff()] = 'bar';
And on the subject of methods and subscripting...
This would appear to work, but it's a bad idea and it doesn't work how you might think:
var obj = {}
;
obj[doStuff] = 'bar';
What happens is doStuff
will coerse as doStuff.toString()
and it would sometimes behave as expected.