如何使用' +'在JSON数据中连接字符串?

时间:2014-08-25 08:40:13

标签: javascript jquery json

我有这样的代码:

jQuery.each(images, function (k, v) {
    v = v.split(':');

    data.questions.push({
        source: questionAssetPath + v[0],
        match: v[1],
        mouse: mouseAssetPath + v[2] + '.png'
    });

    data.answers.push({
        answer: v[1],
        match: v[1]
    });
});

当我运行grunt任务(browserify:js)时,我遇到了这个错误:

ParseError: Unexpected token +

请帮我解决这个问题。

谢谢你。

更新 我自己解决了。多谢你们。我注意到我不能将+运算符用于对象(wtf with me)

images = [
    "maria-ozawa.png:MariaOzawa:1",
    "aoi-125239.png:Aoi:2",
    "sasha-grey.png:SashaGrey:3"
];

jQuery.each(images, function (k, v) {
    v = v.split(':');
    v[0] = questionAssetPath + v[0];
    v[2] = mouseAssetPath + v[2] + '.png';
    data.questions.push({source: v[0], match: v[1], mouse: v[2]});
    data.answers.push({answer: v[1], match: v[1]});
});

2 个答案:

答案 0 :(得分:1)

 Query.each(images, function (k, v) {
        v = v.split(':');
        questionAssetPath = questionAssetPath.concat(v[0])
        data.questions.push({source: questionAssetPath, match: v[1], mouse: mouseAssetPath + v[2] + '.png'});
        data.answers.push({answer: v[1], match: v[1]});
    });

这将消除使用'+'的需要并将解决错误

请参阅JavaScript String concat() Method

答案 1 :(得分:0)

检查您的数据,因为这似乎工作正常:

JSFIDDLE

var images = ["a:b:c","d:e:f"];
var data = {
    questions:[], 
    answers:[]   
};
var questionAssetPath = "c:\\abc\\";
var mouseAssetPath = "c:\\def\\";

$.each(images, function (k, v) {
    v = v.split(':');
    data.questions.push({source: questionAssetPath + v[0], match: v[1], mouse: mouseAssetPath + v[2] + '.png'});
    data.answers.push({answer: v[1], match: v[1]});
});

console.log(data);