如何在JavaScript全局变量中附加多个值并将它们转换为JSON

时间:2023-01-24 09:04:12

I have javascript global variable AdditionalTenentList and I need to append muliple values in it at run time. I need to store value value in such a way that is search able by index and secondly I need to convert into JSON format so that I can post it to my script; say example I am taking 3 values from user at different timing and I want to append it to this variable on index 0,1 and 2

我有javascript全局变量AdditionalTenentList,我需要在运行时在其中附加多个值。我需要以索引搜索的方式存储值值,其次我需要转换为JSON格式,以便我可以将其发布到我的脚本中;比如说我在不同的时间从用户那里获取3个值,我想在索引0,1和2上将它附加到这个变量

<script type="text/javascript">
var AdditionalTenentList = {
    StudentUWLID: ""
};

function () {
    AdditionalTenentList.StudentUWLID = ? ? ? ? ?
}
</script>

2 个解决方案

#1


1  

You can use an Array and the push method:

您可以使用数组和推送方法:

JSFiddle

var AdditionalTenentList = {
    StudentUWLID: []
};

var addElement = function (something) {
    AdditionalTenentList.StudentUWLID.push(something);
}

addElement('x');
addElement('y');
addElement('z');

console.log(AdditionalTenentList);

#2


1  

You could work with a key value pair :

您可以使用键值对:

var obj = {
    key1: value1,
    key2: value2
};

to set you do

设置你做

obj.key3 = "value3"; or obj["key3"] = "value3";

obj.key3 =“value3”;或obj [“key3”] =“value3”;

to retrieve you do

检索你做

var result = obj.key3; or var result = obj["key3"];

var result = obj.key3;或var result = obj [“key3”];

keep in mind that value1 can also be an array for instance, so you can do this then :

请记住,value1也可以是一个数组,所以你可以这样做:

var obj = {
key1: []
}

obj.key1.push("a value");

to convert obj to json you do this : var jsonString = JSON.stringify(obj);

要将obj转换为json,你可以这样做:var jsonString = JSON.stringify(obj);

And to convert back to javascript object you do this : JSON.parse(jsonString);

要转换回javascript对象,你可以这样做:JSON.parse(jsonString);

#1


1  

You can use an Array and the push method:

您可以使用数组和推送方法:

JSFiddle

var AdditionalTenentList = {
    StudentUWLID: []
};

var addElement = function (something) {
    AdditionalTenentList.StudentUWLID.push(something);
}

addElement('x');
addElement('y');
addElement('z');

console.log(AdditionalTenentList);

#2


1  

You could work with a key value pair :

您可以使用键值对:

var obj = {
    key1: value1,
    key2: value2
};

to set you do

设置你做

obj.key3 = "value3"; or obj["key3"] = "value3";

obj.key3 =“value3”;或obj [“key3”] =“value3”;

to retrieve you do

检索你做

var result = obj.key3; or var result = obj["key3"];

var result = obj.key3;或var result = obj [“key3”];

keep in mind that value1 can also be an array for instance, so you can do this then :

请记住,value1也可以是一个数组,所以你可以这样做:

var obj = {
key1: []
}

obj.key1.push("a value");

to convert obj to json you do this : var jsonString = JSON.stringify(obj);

要将obj转换为json,你可以这样做:var jsonString = JSON.stringify(obj);

And to convert back to javascript object you do this : JSON.parse(jsonString);

要转换回javascript对象,你可以这样做:JSON.parse(jsonString);