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
I'm expecting 1 as the result
asked Feb 22, 2020 at 19:48
qadenza
9,34119 gold badges80 silver badges149 bronze badges
2 Answers 2
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
});
answered Feb 22, 2020 at 19:52
harsh_apache
4334 silver badges10 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
qadenza
what about this -
https://www.w3schools.com/jsref/jsref_findindex.aspharsh_apache
see this link, explained very well: stackoverflow.com/questions/41443029/…
If you want to use findIndex(), the params must be function instead of a specific item.
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()
The indexOf() method searches the array for the specified item, and returns its position.
var styles = ['btx btx1', 'btx btx2', 'btx btx3', 'btx btx4'];
let a = 'btx btx2';
let x = styles.indexOf(a);
console.log(x);
answered Feb 23, 2020 at 0:39
Nguyễn Văn Phong
14.2k19 gold badges48 silver badges65 bronze badges
1 Comment
Nguyễn Văn Phong
@qadenza Does this answer your question? Let me know if you need any help
lang-js
indexOfrather thanfindIndex, which expects a function parameter, as the error tells you. VTC as typo/resolved in a way unhelpful to future visitors.https://www.w3schools.com/jsref/jsref_findindex.aspfindIndex. You could do this withstyles.findIndex(e => e === a);but this is a more verbose and less efficient way to writestyles.indexOf(a).