[英]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.