[英]'Unexpected token d' when trying to add objects to a Javascript Object array
[英]Unexpected token { when add object to an array with .map
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;
});
我认为您正在解决这个问题:
有疑问时:
map()方法创建一个新数组,并对该数组中的每个元素调用提供的函数。
这意味着每次地图迭代中的scriptItem变量都是您在scriptList数组中拥有的对象之一。 Map()对变量进行操作,然后返回一个新变量,该变量将被推送到scriptItem将指向的新数组中。
在您的代码中,您将返回2个对象,而不是一个。 但是每个数组元素只能容纳一个对象。 因此,只返回一件事。
var newscript = scriptList.map(function(scriptItem){
console.log(scriptItem)
return {s_name:'jquery', file:proDir(scriptItem.file)}
});
这应该为您完成工作:
var newscript = scriptList.map(function(scriptItem){
console.log(scriptItem);
var name = scriptItem.s_name;
var file = proDir(scriptItem.file);
return {s_name: name, file:file}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.