admin管理员组文章数量:1325761
I am trying to ge to see if an array has an exact match to a value. This is what I have so far but it doesn't work. If I search for 'leo' I should get no result but in this case both items in the array both match the value. Does anyone know how to find if there is an exact match in the array? Thanks
var array = ['leon','leonardo'];
array.indexOf('leo')
I am trying to ge to see if an array has an exact match to a value. This is what I have so far but it doesn't work. If I search for 'leo' I should get no result but in this case both items in the array both match the value. Does anyone know how to find if there is an exact match in the array? Thanks
var array = ['leon','leonardo'];
array.indexOf('leo')
Share
Improve this question
asked Feb 17, 2012 at 21:46
Leonardo AmigoniLeonardo Amigoni
2,3275 gold badges25 silver badges37 bronze badges
2
-
1
indexOf()
gives-1
for me. jsfiddle/WX737 – ldiqual Commented Feb 17, 2012 at 21:49 - "leo" is not exactly matching any of the values in the array, why do you expect it to be something other than -1? – Yaron U. Commented Feb 17, 2012 at 22:03
3 Answers
Reset to default 5The code you have should work just fine. How are you checking the result?
array.indexOf('leo')
will return -1
if no match is found.
I believe in your real code (not your example) you accidentally have a string instead of an array.
Calling indexOf('ab')
and indexOf('abcd')
on the string 'abcd' will result in both finding a match (returning > -1).
Both would return 0 as they match at the start.
I think You can use array.find()
instead of array.indexOf()
to solve your problem.
本文标签: Javascript Array exact matchStack Overflow
版权声明:本文标题:Javascript: Array exact match - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742190896a2430192.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论