JavaScript搜索一个以某个值开头的值的数组
我正在寻找一种搜索数组的方法,以查看是否存在从搜索词开始的值。
const array1 = ['abc','xyz'];
因此,搜索“ ABCD”将在上述返回。
我一直在玩,但这似乎只能检查全部价值。 另外,我认为startswith我不认为会检查字符串而不是数组中的值吗?
I am looking for a way to search an array to see if a value is present that starts with the search term.
const array1 = ['abc','xyz'];
So a search for 'abcd' would return true on the above.
I have been playing about with includes, but that only seems to check the full value.
Also, startsWith I dont think will work as I believe that checks a string and not values in an array??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 函数允许您在参数中传递自定义功能,该功能将在每个值上进行测试。这样,您可以按照您的意愿在数组的每个值上使用
startswith()
。例子:
如果要返回
true
或false
而不是值,则可以检查返回的值是否不同于undefined
。带布尔值的同一片段:
You can use the
find()
function which allows you to pass a custom function in parameter that will be tested on each value. This way you can usestartsWith()
on each value of the array as you intended to do.Example:
If you want to return
true
orfalse
instead of the value, you can check if the returned value is different fromundefined
.The same snippet with a boolean: