如何找到数组元素的索引

时间:2020-02-22 19:48:27

标签: javascript jquery

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
});

错误-Uncaught TypeError: btx btx2 is not a function

我期望得到1

2 个答案:

答案 0 :(得分:3)

使用indexOf:

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

答案 1 :(得分:1)

如果要使用findIndex(),则参数必须是功能而不是特定项。

语法

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);

或使用indexOf()

indexOf()方法在数组中搜索指定的项目,然后 返回其位置。

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

let a = 'btx btx2';
let x = styles.indexOf(a);

console.log(x);