jQuery.inArray()
在数组中查找指定值并返回它的索引(如果没有找到,则返回-1)。
jQuery.inArray(value, array[, fromIndex ])
- value类型: Anything。要查找的值。
- array类型: Array。一个数组,通过它来查找。
- fromIndex类型: Number。数组索引值,表示从哪里在开始查找。默认值是0,这将查找整个数组。
$.inArray()
方法类似于JavaScript的原生.indexOf()
方法,没有找到匹配元素时它返回-1。如果数组第一个元素匹配value
(参数),那么$.inArray()
返回0。
因为JavaScript将0视为false(即 0 == false,但是 0 !== false),要检查在array
中是否存在value
,你需要检查它是否不等于(或大于)-1。
值之间的比较是严格比较(注:即,===或!==比较)。下面这段代码返回-1
(没有找到),因为字符串数组中不可能找到一个数字:
$.inArray( 5 + 5, [ "8", "9", "10", 10 + "" ] );
例子
返回数组中指定元素的索引值。
<!DOCTYPE html> <html> <head> <style> div { color:blue; } span { color:red; } </style> <script src="https://www.lanmper.cn/static/js/jquery-3.5.0.js"></script> </head> <body> <div>"John" found at <span></span></div> <div>4 found at <span></span></div> <div>"Karl" not found, so <span></span></div> <div>"Pete" is in the array, but not at or after index 2, so <span></span></div> <script>var arr = [ 4, "Pete", 8, "John" ];var $spans = $("span"); $spans.eq(0).text(jQuery.inArray("John", arr)); $spans.eq(1).text(jQuery.inArray(4, arr)); $spans.eq(2).text(jQuery.inArray("Karl", arr)); $spans.eq(3).text(jQuery.inArray("Pete", arr, 2)); </script> </body> </html>
"John" found at
4 found at
"Karl" not found, so
"Pete" is in the array, but not at or after index 2, so