Javascript javascript对象变量键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6071471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:07:11  来源:igfitidea点击:

javascript object variable key

javascriptjquery

提问by salmane

I am creating a plugin for Jquery and need to have a variable as a key in an object.

我正在为 Jquery 创建一个插件,需要有一个变量作为对象中的键。

$(selector).animate({self.settings.direction: '+='+self.displacement+'px'}, "slow" , function () {});

this part causes the error:

这部分导致错误:

self.settings.direction

self.settings.direction

any ideas where my syntax is wrong? thank you

我的语法错误的任何想法?谢谢你

回答by Amadan

AFAIK, you can't. Whatever is in front of the colon in the object literal notation will be automatically interpreted as a string. You will need to construct your object beforehand, and use the square bracket notation.

AFAIK,你不能。对象文字符号中冒号前面的任何内容都将被自动解释为字符串。您需要事先构造对象,并使用方括号表示法。

var options = {}
options[self.settings.direction] = '+=' + self.displacement + 'px';
$(selector).animate(options, "slow" , function () {});

回答by Ronald

If the value is also a string you could use JSON.parse:

如果该值也是一个字符串,您可以使用 JSON.parse:

var a = 'key';
var b = 'value';
var test = JSON.parse('{"' + a + '":"' + b + '"}"');
//test = {key: 'value'}

回答by Mathieu

You can access the string defined by a variable with toString(). so :

您可以使用 toString() 访问由变量定义的字符串。所以 :

var obj = new Object;

obj.a = 0;
obj.b = 1;

var a = "b";

obj["a"]; // will output 0
obj[a.toString()] // will output 1

回答by rciq

Keep in mind you are defining an object there between the curly brackets. You can't use dots in property names. Assuming the displacement property is set somewhere else earlier, this will work for you:

请记住,您正在大括号之间定义一个对象。您不能在属性名称中使用点。假设置换属性设置在其他地方更早,这对你有用:

$(selector).animate({settings: {direction: '+='+self.displacement+'px'}}, "slow" , function () {})