简体   繁体   English

检索变量值而不是此变量的名称

[英]Retrieve variable value and not name of this variable

I'm trying to add a value to a json structure like : 我正在尝试将值添加到json结构中,例如:

saveChamp.test = {"type":"","text":""};

It's ok, but i want "test" like : var test = $('blablabla').val(); 没关系,但是我想要“测试”,例如: var test = $('blablabla').val();

In my example, it does not fetch the value of test but it creates an entry with the name test. 在我的示例中,它不会获取test的值,但是会创建一个名称为test的条目。 This is not what I want. 这不是我想要的。

Help ? 救命 ?

Edit : 编辑:

var saveChamp = new Object();
var test = "Field1";
saveChamp.test = {"type":"ok","text":"kok"};

I want that script create an entry in saveChamp with the name Field1 (value of ma variable test). 我希望该脚本在saveChamp中创建一个名为Field1(ma变量test的值)的条目。

Ahh, in this case, after your edit it's obvious what you need. 嗯,在这种情况下,编辑后很明显您需要什么。

every object in javascript can be treated as an associative array, and it is possible to call properties of an array by a variable's value.. javascript中的每个对象都可以视为关联数组,并且可以通过变量的值来调用数组的属性。

var saveChamp = new Object();
var test = "Field1";
saveChamp[test] = {"type":"ok","text":"kok"};

this is the same as: 这与:

saveChamp["Field1"] = {"type":"ok","text":"kok"};

this will do what you want, as the name of the field is passed as a variable string. 这将完成您想要的操作,因为字段名称作为变量字符串传递。

Not sure i understand you fully, as this code doesn't make much sense. 不确定我是否完全理解您,因为此代码没有多大意义。

JSON means Javascript Object Notation . JSON表示Javascript对象符号

It is used to transfer variables through plain text. 它用于通过纯文本传输变量。 you do not need this, as you can transfer you data via code. 您不需要这样做,因为您可以通过代码传输数据。

ex. 例如 1: 1:

saveChamp.test = $('blablabla')).val();

will make the object saveChamp, have a property test, which has a value: $('blablabla')).val(); 将使对象saveChamp进行属性测试,其值是:$('blablabla'))。val();

ex. 例如 2: 2:

saveChamp.test = {"type":"blablabla","text":$('blablabla')).val()};

will hopefully create an object, out of saveChamp's test property. 有望从saveChamp的测试属性中创建一个对象。 this actually means this: 这实际上意味着:

saveChamp.test.type = "blabalbla"; 
saveChamp.test.text = $('blablabla')).val();

EDIT 编辑

i made a new answer, but leaving this one here, as they are both very different, and both useful. 我提出了一个新的答案,但将其保留在这里,因为它们都非常不同,并且都非常有用。

Try using the bracket notation: 尝试使用括号表示法:

var test = $('blablabla').val();
saveChamp[test] = {
    "type": "",
    "text": ""
};

I see how you are trying to set your value and set is to a JSON object but if that is the exact code you are using it is missing the "#" to grab the element by Id and there is an extra paren; 我知道您是如何尝试设置值并将其设置为JSON对象的,但是如果这是您使用的确切代码,则会丢失“#”以通过ID来获取元素,并且会有一个多余的括号。

Trey using: Trey使用:

var test = $('#blablabla').val(); 

saveChamp.test = {"type": "blablabla","text": test};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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