Javascript 比较后返回匹配的元素(小写)?
我有这个阵列:Javascript 比较后返回匹配的元素(小写)?,javascript,jquery,arrays,underscore.js,lodash,Javascript,Jquery,Arrays,Underscore.js,Lodash,我有这个阵列: var mainArray=[“Title”、“AssignedTo”、“IssueStatus”、“Priority”、“Comment”、“Category”、“RelatedIssues”、“v3 comments”、“TaskDueDate”、“Attachments”] 我需要通过将这些元素与小写等价物进行比较来找到它们 var字段=[“标题”,“注释”] 基本上,我需要找出字段是否包含在main数组中,并从该数组返回大写值:[“Title”,“Comment”]如果字
var mainArray=[“Title”、“AssignedTo”、“IssueStatus”、“Priority”、“Comment”、“Category”、“RelatedIssues”、“v3 comments”、“TaskDueDate”、“Attachments”]
我需要通过将这些元素与小写等价物进行比较来找到它们
var字段=[“标题”,“注释”]代码>
基本上,我需要找出字段是否包含在main数组中,并从该数组返回大写值:[“Title”,“Comment”]
如果字段数组中包含小写值,则可以在检查后过滤该值
var mainArray=[“标题”、“分配给”、“发布状态”、“优先级”、“评论”、“类别”、“相关问题”、“v3命令”、“任务截止日期”、“附件”],
字段=[“标题”,“注释”],
result=mainArray.filter(a=>fields.includes(a.toLowerCase());
控制台日志(结果)代码>只需运行array with for(),并根据需要在外部变量中收集结果,如下所示:
var need = [];
for(var i in yourArray){
if(){ // compare function
// add to "Need" array
}
}
// print the result
此外,还可以将其包装到函数中。
如果阵列较大,最好使用过滤器。但是如果你有一个巨大的数组,最好使用ajax和后端脚本。你可以使用这个ES6函数,它利用映射来获得更好的性能:
函数getMatches(a,b){
var mp=newmap(a.Map(s=>[s.toLowerCase(),s]);
返回b.map(mp.get,mp);
}
//示例数据和调用
var mainArray=[“标题”、“分配给”、“问题状态”、“优先级”、“评论”、“类别”、“相关问题”、“v3命令”、“任务截止日期”、“附件”];
变量字段=[“标题”,“注释”];
log(getMatches(mainArray,fields))
您可以使用Array#filter
方法。见下文
var mainArray=[“Title”、“AssignedTo”、“IssueStatus”、“Priority”、“Comment”、“Category”、“RelatedIssues”、“v3 comments”、“TaskDueDate”、“Attachments”];
变量字段=[“标题”,“注释”];
var res=mainArray.filter(函数(v,i){
返回字段。包括(v.toLowerCase());
});
控制台日志(res)代码>您尝试了什么?是一个只有一个字符串的数组吗?很抱歉,这是一个拼写错误mainArray.filter(x=>fields.includes(x.toLowerCase())代码>至少显示您尝试了什么…问题不是那么复杂吗?为什么if语句?只需返回条件的结果。此外,您还可以使用includes
和一个箭头函数。includes
可以使用,但它并没有得到广泛支持:[它在除IE之外的所有主要浏览器上都受支持。@AndrewLi您是对的,但看看这个:对于旧浏览器,我们需要使用polyfill。
var need = [];
for(var i in yourArray){
if(){ // compare function
// add to "Need" array
}
}
// print the result