我有一个数组,里面有这样的数组;
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"]
];
如果 line[4] 正是搜索语句,例如“A man is Walking”,则使用 Underscore,我可以在“lines”内获取一个数组。将返回行[0];
所以我希望能够只用一个单词搜索这些句子(行),比如“Walking”应该匹配并返回“lines”中的第一个数组,因为有一个句子包含该单词。
_.some(lines, function(array){
var result = (array[4] == 'walking' && array[4]);
if (result !== false){
console.log(result);
}
});
我如何修改这个下划线函数,或者是否应该使用正确的函数,或者如果有的话,即使它没有下划线,请提出建议。
最佳答案
假设你没有 ES6 的 find 功能,用简单的 javascript 表示:
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"));
应该给出:
{
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"]]
}
关于javascript - 下划线返回数组中对象的索引,其中单词存在于对象内的句子中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29154830/