[英]How to Check All Array Element Inside endswith()
let array1 = ["?", "!", "."]; let array2 = ["live.", "ali!", "harp", "sharp%", "armstrong","yep?"]; console.log(array2.filter((x) => x.endsWith("?")));
The output is just: ['yep?']
输出只是:
['yep?']
Because the function endsWith()
only checked for "?"
因为函数
endsWith()
只检查了"?"
as you see in the code.正如您在代码中看到的那样。 How do I loop the elements on the
array1
(suffixes) inside the endsWith
function so the output is:如何在
endsWith
函数内循环array1
(后缀)上的元素,以便输出为:
['live.', 'ali!', 'yep?']
You could use a regex , and then match
each element in the filter
iteration against it.您可以使用regex ,然后将
filter
迭代中的每个元素与之match
。
/[?!.]$/
says match one of these things in the group ( [?!.]
) before the string ends ( $
). /[?!.]$/
表示在字符串结束( $
)之前匹配组中的这些东西之一( [?!.]
)。
const arr = ['live.', 'ali!', 'harp', 'sharp%', 'armstrong', 'yep?']; const re = /[?!.]$/; const out = arr.filter(el => el.match(re)); console.log(out);
Regarding your comment you can pass in a joined array to the RegExp constructor using a template string .关于您的评论,您可以使用模板字符串将连接数组传递给RegExp 构造函数。
const query = ['.', '?', '!']; const re = new RegExp(`[${query.join('')}]$`); const arr = ['live.', 'ali!', 'harp', 'sharp%', 'armstrong', 'yep?']; const out = arr.filter(el => el.match(re)); console.log(out);
You can use an inner .some()
call to loop over your array1
and return true
from that when you find a match instead of hardcoding the ?
您可以使用内部
.some()
调用循环遍历您的array1
并在找到匹配项时从该调用返回true
,而不是硬编码?
: :
const array1 = ["?", "!", "."]; const array2 = ["live.", "ali!", "harp", "sharp%", "armstrong","yep?"]; const res = array2.filter((x) => array1.some(punc => x.endsWith(punc))); console.log(res);
Above, when you return true
(or a truthy value) from the .some()
callback, the .some()
method will return true
, otherwise it will return false
if you never return true, thus discarding it.上面,当您从
.some()
回调返回true
(或真值)时, .some()
方法将返回true
,否则如果您从不返回 true ,它将返回false
,从而丢弃它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.