简体   繁体   English

如何找到数组元素的索引

[英]how to find index of an array element

var styles = ['btx btx1', 'btx btx2', 'btx btx3', 'btx btx4'];

$('#mst').on('click', function(){
    let a = $('#btx').attr('class');
    console.log(a);  // `btx btx2`
    let x = styles.findIndex(a);
    console.log(x);  // error
});

error - Uncaught TypeError: btx btx2 is not a function错误 - 未捕获类型错误Uncaught TypeError: btx btx2 is not a function

I'm expecting 1 as the result我期待1作为结果

Use indexOf:使用索引:

$('#mst').on('click', function(){
   let a = $('#btx').attr('class');
   console.log(a);  // `btx btx2`
   let x = styles.indexOf(a);
   console.log(x);  // error
});

If you want to use findIndex() , the params must be function instead of a specific item.如果要使用findIndex() ,参数必须是function而不是特定项目。

Syntax句法

array.findIndex(function(currentValue, index, arr), thisValue)

 var styles = ['btx btx1', 'btx btx2', 'btx btx3', 'btx btx4']; let a = 'btx btx2'; let x = styles.findIndex(function(currentValue, index, arr){ return currentValue === a; }); console.log(x);

Or use indexOf()或者使用indexOf()

The indexOf() method searches the array for the specified item , and returns its position. indexOf() 方法在数组中搜索指定的项目,并返回其 position。

 var styles = ['btx btx1', 'btx btx2', 'btx btx3', 'btx btx4']; let a = 'btx btx2'; let x = styles.indexOf(a); console.log(x);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM