找出JavaScript数组是否包含给定字符串的子字符串的最有效方法是什么?
例如,如果我有一个JavaScript数组
var a = ["John","Jerry","Ted"];
在将上述数组与字符串进行比较时,我需要返回true
的条件:
"John Elton"
答案 0 :(得分:4)
您可以使用.some()
和.includes()
方法:
let arr = ["John","Jerry","Ted"];
let str = "John Elton";
let checker = (arr, str) => arr.some(s => str.includes(s));
console.log(checker(arr, str));
答案 1 :(得分:4)
对于ES6:
var array = ["John","Jerry","Ted"];
var strToMatch = "John Elton"
array.some(el => strToMatch.includes(el))
答案 2 :(得分:0)
如果您不能使用ES6:
>>> from itertools import islice
>>> l1=[1,2,3,4,5,7,8,9,23,32,33]
>>> l2=[5,3,1,2]
>>> it = iter(l1)
>>> [list(islice(it, n)) for n in l2]
[[1, 2, 3, 4, 5], [7, 8, 9], [23], [32, 33]]