jQuery.inArray()

jQuery.inArray( value, array ) 官网原E文: Number

描述: 搜索数组中指定值并返回它的索引(如果没有找到则返回-1)。

  • version added: 1.2jQuery.inArray( value, array )

    value要搜索的值。

    array一个数组,通过它来搜索。

$.inArray()方法类似于JavaScript的原生.indexOf()方法,没有找到匹配元素时它返回-1。如果数组第一个元素在匹配value$.inArray()返回0。

因为JavaScript将0视为false(即 0 == false, 但是 0 !== false),如果我们检查在array中存在value,我们只需要检查它是否不等于(或大于)-1。

Example:

Report the index of some elements in the array.

<!DOCTYPE html>
<html>
<head>
  <style>
  div { color:blue; }
  span { color:red; }
</style>
  <script src="http://code.jquery.com/jquery-latest.min.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>
<script>var arr = [ 4, "Pete", 8, "John" ];

$("span:eq(0)").text(jQuery.inArray("John", arr));
$("span:eq(1)").text(jQuery.inArray(4, arr));
$("span:eq(2)").text(jQuery.inArray("Karl", arr));

</script>

</body>
</html>

Demo:

jQuery 1.6 API 中文版Clove整理、修订