Javascript 下划线在数组中返回对象的索引,其中单词存在于对象中的句子中
我有一个数组,里面有这样的数组Javascript 下划线在数组中返回对象的索引,其中单词存在于对象中的句子中,javascript,arrays,search,underscore.js,indexof,Javascript,Arrays,Search,Underscore.js,Indexof,我有一个数组,里面有这样的数组 var lines = [ ["1","1","1","A man is walking."] ,["1","1","2","Noooo he's not, no way!"], ["1","1","3","You can't see that far can you?"], ["1","1","4","I can, he stopped, he's looking right at us"] ]; 如果第[4]行正好是搜索语句,比如“一个男人在走路”,
var lines = [
["1","1","1","A man is walking."]
,["1","1","2","Noooo he's not, no way!"],
["1","1","3","You can't see that far can you?"],
["1","1","4","I can, he stopped, he's looking right at us"]
];
如果第[4]行正好是搜索语句,比如“一个男人在走路”,我可以用下划线在“lines”内得到一个数组,它将返回第[0]行
所以我希望能够用一个单词搜索这些句子(行),比如“Walking”应该匹配并返回“lines”中的第一个数组,因为有一个句子包含这个单词
_.some(lines, function(array){
var result = (array[4] == 'walking' && array[4]);
if (result !== false){
console.log(result);
}
});
如何修改此下划线函数,或者如果有正确的下划线函数应该使用,或者即使它没有下划线,也请提出建议。
。
某些函数返回布尔值。您需要通过查看搜索词是否在字符串中来过滤匹配结果。索引开始于0
,因此您需要检查索引3而不是4
工作示例:
var行=[
[“1”、“1”、“1”、“一个男人正在走路。”],
[“1”,“1”,“2”,“不,他不是,不可能!”,
[“1”,“1”,“3”,“你看不到那么远,是吗?”,
[“1”,“1”,“4”,“我能,他停下来了,他正看着我们”]
];
var input=document.getElementById('search');
var output=document.getElementById('output');
input.onkeyup=函数(事件){
var值=此值;
var results=\过滤器(行、函数(数组){
返回数组[3],indexOf(value)>-1;
});
变量索引=551;.map(结果、函数(数组){
返回行。indexOf(数组);
});
output.innerHTML='索引:'+JSON.stringify(索引)+''+JSON.stringify(结果,null,2)+'';
var lines = [
["1","1","1","A man is walking."],
["1","1","2","Noooo he's not, no way!"],
["1","1","3","You can't see that far can you?"],
["1","1","4","I can, he stopped, he's looking right at us"]
];
function lineSearch(arr, term) {
var indices = arr.map(function(innerArr, index) {
return innerArr[3].indexOf(term) > -1 ? index : null;
}).filter(function(x) {
return x !== null;
});
var results = arr.map(function(innerArr, index) {
return innerArr[3].indexOf(term) > -1 ? innerArr : null;
}).filter(function(x) {
return x !== null;
});
return {indices: indices, results: results};
}
console.log(lineSearch(lines, "can"));
};代码>
假设您没有ES6的查找功能,使用纯javascript:
应提供:
这确实会返回出现“walking”的行,但它只返回第一个找到的数组,它应该继续迭代并返回其余的数组及其索引。我已经更新了我的答案以满足您现在的需求。检查了答案,速度快得多,如果您使用ES6的“查找”,您将如何执行?我写了关于查找的部分,当时我以为您只是在查找第一个找到的结果。所以在你的情况下,它实际上并不有用。它基本上是一个更高效的过滤器版本,它在回调中找到满足条件的第一个元素后停止。您可以在此处找到有关该功能的更多详细信息:
{
indices: [2, 3],
results: [["1", "1", "3", "You can't see that far can you?"], ["1", "1", "4", "I can, he stopped, he's looking right at us"]]
}