_.indexOf() 函数:
- 它给出了我们需要找到其位置的元素的索引。
- 它从 0 开始计算数组中元素的位置。
- 如果数组中不存在该元素,则结果将为-1。
用法:
_.indexOf(array, value, [isSorted])
参数:
它需要三个参数:
- array
- value
- isSorted (optional)
返回值:
它返回传递元素的位置。
例子:
- 将数字列表传递给 _.indexOf() 函数:
._indexOf() 函数从列表中一个一个地取出元素,并检查它是否等于第二个参数中传递的元素。如果相等,则结果是它的索引,否则返回 -1。<html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script> </head> <body> <script type="text/javascript"> console.log(_.indexOf([1, 2, 3, 4, 5, 6], 4)); </script> </body> </html>
输出:
- 将字符列表传递给 _.indexOf() 函数:
我们还可以将字符列表传递给 _.indexOf() 函数,它的工作方式与数字列表的工作方式相同。在第二个参数中,我们需要提到我们需要在单引号内找到其索引的单词,“。<html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script> </head> <body> <script type="text/javascript"> console.log(_.indexOf(['HTML', 'CSS', 'JS', 'AJAX', 'PEARL'], 'AJAX')); </script> </body> </html>
输出:
- 传递列表中不存在的第二个参数::
将字符元素列表传递给 _.indexOf() 函数。因为在给定列表中,第二个参数“GEEKS”不存在,所以结果将为-1。<html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script> </head> <body> <script type="text/javascript"> console.log(_.indexOf(['HTML', 'CSS', 'JS', 'AJAX', 'PEARL'], 'GEEKS')); </script> </body> </html>
输出:
- 将包含重复元素的列表传递给 _.indexOf() 函数:即使我们传递一个包含重复元素的数组,_.indexOf() 函数也会以相同的方式工作,并返回首先找到第二个参数中传递的元素的索引。
<html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script> </head> <body> <script type="text/javascript"> console.log(_.indexOf(['HTML', 'CSS', 'JS', 'AJAX', 'PEARL', 'CSS', 'HTML', 'CSS'], 'CSS')); </script> </body> </html>
输出:
笔记:
这些命令在 Google 控制台或 Firefox 中不起作用,因为需要添加他们没有添加的这些附加文件。
因此,将给定的链接添加到您的 HTML 文件中,然后运行它们。
链接如下:
<script type="text/javascript"
src ="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js">
</script>
一个例子如下所示:
相关用法
- Javascript String indexOf()用法及代码示例
- JavaScript Array indexOf()用法及代码示例
- Javascript typedArray.indexOf()用法及代码示例
- Typescript String indexOf()用法及代码示例
- Typescript Array indexOf()用法及代码示例
- Lodash _.indexOf()用法及代码示例
- p5.js year()用法及代码示例
- d3.js d3.utcTuesdays()用法及代码示例
- d3.js d3.map.set()用法及代码示例
- Tensorflow.js tf.layers.embedding()用法及代码示例
注:本文由纯净天空筛选整理自Sakshi98大神的英文原创作品 Underscore.js _.indexOf() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。