【问题标题】:how to find index of an array element如何找到数组元素的索引
【发布时间】:2020-02-22 19:48:27
【问题描述】:
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 作为结果

【问题讨论】:

  • 我认为您的意思是indexOf,而不是findIndex,即expects a function parameter,正如错误告诉您的那样。 VTC 错字/以对未来访问者无益的方式解决。
  • @ggorlen - 这个怎么样 - https://www.w3schools.com/jsref/jsref_findindex.asp
  • 怎么样?它说的和上面一样,就是你需要将一个函数传递给findIndex。您可以使用styles.findIndex(e => e === a); 来执行此操作,但这是编写styles.indexOf(a) 的更冗长且效率更低的方式。

标签: javascript jquery


【解决方案1】:

使用 indexOf:

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

【讨论】:

【解决方案2】:

如果你想使用findIndex(),参数必须是function而不是具体的item。

语法

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

【讨论】:

  • @qadenza 这能回答你的问题吗?如果您需要任何帮助,请告诉我
猜你喜欢
  • 1970-01-01
  • 2012-11-24
  • 2011-06-25
  • 1970-01-01
  • 2010-12-04
  • 2017-06-01
  • 1970-01-01
  • 2021-10-27
  • 1970-01-01
相关资源
最近更新 更多