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

錯誤 - 未捕獲類型錯誤Uncaught TypeError: btx btx2 is not a function

我期待1作為結果

使用索引:

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

如果要使用findIndex() ,參數必須是function而不是特定項目。

句法

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() 方法在數組中搜索指定的項目,並返回其 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