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

本文标签: Javascript Array exact matchStack Overflow