Javascript 检查数组';s字符串显示为另一个数组的一部分';s弦
我有一个字符串数组,如下所示:Javascript 检查数组';s字符串显示为另一个数组的一部分';s弦,javascript,arrays,string,data-structures,string-comparison,Javascript,Arrays,String,Data Structures,String Comparison,我有一个字符串数组,如下所示: var inputArray= [ "Bob Johnson goes to the zoo", "Timothy Smith likes to eat ice-cream", "Jenny wants to play with her friends", "There is no one in the room to play with Timothy", "Jeremy Jones has been sleeping
var inputArray= [
"Bob Johnson goes to the zoo",
"Timothy Smith likes to eat ice-cream",
"Jenny wants to play with her friends",
"There is no one in the room to play with Timothy",
"Jeremy Jones has been sleeping all day"
];
var names = [
"bob johnson",
"bob",
"timothy smith",
"timothy",
"jenny sanderson",
"jenny",
"jeremy jones",
"jeremy"
];
…和另一组名称,如:
var inputArray= [
"Bob Johnson goes to the zoo",
"Timothy Smith likes to eat ice-cream",
"Jenny wants to play with her friends",
"There is no one in the room to play with Timothy",
"Jeremy Jones has been sleeping all day"
];
var names = [
"bob johnson",
"bob",
"timothy smith",
"timothy",
"jenny sanderson",
"jenny",
"jeremy jones",
"jeremy"
];
…我要做的是检查inputArray中的每个字符串,看看它们是否包含names数组中的任何名称
每当发现名称匹配时,它都应该做两件事:
var output = [];
for(var c in inputArray){
output[c] = inputArray[c].toLowerCase();
for(var o in names){
output[c] = output[c].replace(names[o],"?");
}
}
此处是预期的输出数组。在这种情况下,您需要使用嵌套for循环,然后检查子字符串
var answerKey = [], output = [];
for(var i = 0; i < inputArray.length; i++){
for(var j = 0, len = names.length; j < len; j++){
if(inputArray[i].toLowerCase().indexOf(names[j]) > -1){
answerKey.push(names[j])
output.push(inputArray[i].toLowerCase().replace(names[j], '?'))
}
}
}
var-answerKey=[],output=[];
for(变量i=0;i-1){
answerKey.push(姓名[j])
output.push(inputArray[i].toLowerCase().replace(名称[j],'?'))
}
}
}
使用和获取帮助:
var inputArray = [
"Bob Johnson goes to the zoo",
"Timothy Smith likes to eat ice-cream",
"Jenny wants to play with her friends",
"There is no one in the room to play with Timothy",
"Jeremy Jones has been sleeping all day"
];
var names = [
"Bob Johnson",
"Bob",
"Timothy Smith",
"Timothy",
"Jenny Sanderson",
"Jenny",
"Jeremy Jones",
"Jeremy"
];
var answers = [];
var outputArr = inputArray.map(function(row){
var matches = names.filter(function(name){ return row.indexOf(name) > -1 });
matches.forEach(function(match){ answers.push(match); row = row.replace(match, '?')});
return row;
});
console.log('answers: ' + answers);
console.log('outputArr: ' + outputArr);
顺便说一句,如果名称数组是小写的,只需使用toLowerCase
.看起来像是家庭作业!