javascript中的多行变量

时间:2014-09-23 19:18:40

标签: javascript

我正在尝试使用数组中的一些数据来创建这个javascript变量,但我无法找到正确的语法来使其工作..

certifications will be "Win7,Win8,PDI"

var myArray = certifications.split(",");

var data = "[{" +
        for (var i in myArray)
        " "id":i,"text":myArray[i]}, " +
        "}]";

我希望将我的数据变量看起来像:

var data = "[{"id":0,"text":Win7},{"id":1,"text":Win8},{"id":2,"text":PDI}]";

2 个答案:

答案 0 :(得分:5)

试试这个:

var data = JSON.stringify(certifications.split(",").map(function(value, index) {
    return {
        id: index,
        text: value
    };
}));

答案 1 :(得分:2)

也许+ =是你要找的东西:

var certifications = "Win7,Win8,PDI";
var myArray = certifications.split(",");
var data = "[{";

for (var i in myArray) {
    data += " " +
    "id" +":"+i+","+
    "text" + ":"+myArray[i]+"}, ";
}
data += "}]";