var $scope={};
var componentsDir="/root/";
var appPrefix="/app/";


var scriptRef=[];
function proDir(scriptName){
    return componentsDir+appPrefix+'-home-components/pro/js/'+scriptName+'.js';
};

var scriptList =[
            {s_name:'jquery',file:"jquery.js"},
            {s_name:'bootstrap',file:"bootstrap.min.js"},
            {s_name:'easing',file:"jquery.easing.min.js"},
            {s_name:'fittext',file:"jquery.fittext.js"},
            {s_name:'wow',file:"wow.min.js"},
            {s_name:'creative', file:"creative.js"},

            /*{bootstrap :"bootstrap.min.js"},
            {easing :"jquery.easing.min.js"},
            {fittext :"jquery.fittext.js"},
            {wow :"wow.min.js"},
            {creative :"creative.js"},*/
        ]



var newscript = scriptList.map(function(scriptItem){
    console.log(scriptItem)
    return {{scriptItem.s_name:'jquery'},{scriptItem.file:proDir(scriptItem.file)}},
});

console.log(newscript)


我尝试找到一种方法来遍历脚本列表,并使用.map向每个元素添加额外的目录信息。但是我得到一个错误

Uncaught SyntaxError: Unexpected token {


我尝试将每个元素作为新的newscript数组的对象返回

最佳答案

{在JSON中{之后不是有效字符。

替换此行:

return {{scriptItem.s_name:'jquery'},{scriptItem.file:proDir(scriptItem.file)}}


用这一行:

return {"scriptItem.s_name": 'jquery', "scriptItem.file": proDir(scriptItem.file)}


或另一个变体可能是:

return {
    scriptItem: {
        s_name: 'jquery',
        file: proDir(scriptItem.file)
    }
};


这是您在注释中要求的变体“我想像这样访问newscript的位置值:newscript.jquery”:

var newscript = scriptList.map(function(scriptItem) {
    var returnval = {};
    returnval[ scriptItem.s_name ] = scriptItem.file;
    return returnval;
});


我认为您正在解决这个问题:

How can i name object "keys" programmatically in JavaScript?

有疑问时:

http://jsonlint.com/

09-05 18:08