Javascript 将对象添加到具有.map的数组时出现意外标记{
我试图找到一种方法来循环遍历脚本列表,并使用Javascript 将对象添加到具有.map的数组时出现意外标记{,javascript,arrays,object,dictionary,Javascript,Arrays,Object,Dictionary,我试图找到一种方法来循环遍历脚本列表,并使用.map向每个元素添加额外的dir信息。但是我得到了一个错误 var $scope={}; var componentsDir="/root/"; var appPrefix="/app/"; var scriptRef=[]; function proDir(scriptName){ return componentsDir+appPrefix+'-home-components/pro/js/'+scriptName+'.js'; };
.map
向每个元素添加额外的dir信息。但是我得到了一个错误
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)
我尝试将每个元素作为新的
newscript
数组的对象返回{
在JSON中{
之后不是有效字符
替换此行:
Uncaught SyntaxError: Unexpected token {
return {{scriptItem.s_name:'jquery'},{scriptItem.file:proDir(scriptItem.file)}}
这一行:
Uncaught SyntaxError: Unexpected token {
return {{scriptItem.s_name:'jquery'},{scriptItem.file:proDir(scriptItem.file)}}
或者另一种变体可能是:
return {"scriptItem.s_name": 'jquery', "scriptItem.file": proDir(scriptItem.file)}
下面是您在评论“我想像这样访问newscript的位置值:newscript.jquery”时要求的变体:
我认为你遇到了这个问题:
如有疑问:
map()方法创建一个新数组,其结果是对该数组中的每个元素调用提供的函数
这意味着每次映射迭代中的scriptItem变量都是scriptList数组中的对象之一。map()对该变量进行操作,并返回一个新变量,该变量将被推送到scriptItem将指向的新数组中
在您的代码中,您将返回两个对象,而不是一个。但是每个数组元素只能包含一个对象。因此,只返回一个对象
var newscript = scriptList.map(function(scriptItem) {
var returnval = {};
returnval[ scriptItem.s_name ] = scriptItem.file;
return returnval;
});
这将为您完成以下工作:
var newscript = scriptList.map(function(scriptItem){
console.log(scriptItem)
return {s_name:'jquery', file:proDir(scriptItem.file)}
});
现在出现了“Uncaught SyntaxError:意外令牌”错误。@Chen我更新了答案以修复此问题。问题是需要引用具有特殊字符的键,但我希望访问newscript的位置值,如下所示:newscript.jquery然后我转到dir位置。相反,现在我必须执行newscript[0].file。我确实将return更改为return{[name]:file},但仍然必须执行newscript[0].jquery。我想知道是否可以删除[0]如何使用“jquery”作为索引?谢谢,我现在明白你的意思了。我更新了答案。检查最后一个变量。诀窍在于对javascript对象使用括号表示法,这允许你在设置键时对语句进行求值。另外,官方文档是你最好的朋友:)