最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript: Array exact match - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 5

The 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.

发布评论

评论列表(0)

  1. 暂无评论