I'm bored and messing with my console and I came up with the following code:

I was trying something like:

x = 16;
y = 26;
f = { x+y:"String!"};

expecting something or somehow to do:

Object {1626: "String!"}

Or at least

Object {42: "String!"}

I ended up with

x = 16;
y = 26;
eval("f = { "+x+y+":\"String!\"}");

Which returned as expected:

Object {1626: "String!"}

I've always been told to avoid eval() and never even think about using it due to something about security. Is there a way to use variables in declaring the property (Sorry if I don't know what it's called exactly)

有帮助吗?

解决方案 2

I made this exact same mistake when I started learning JavaScript: JavaScript set object key by variable

You first must make the object:

var f = {};

Then you can use variables to dynamically create keys:

var x = 16, y = 26;
f[x+y] = "Integer"; 
f[x.toString() + y.toString()] = "String";

其他提示

x = 16;
y = 26;
f = {};
f[x+''+y] = "String!"; // For f[1626]

or

f[x+y] = "String!"     // For f[42]
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top