1
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

3
  • 1
    I think you meant indexOf rather than findIndex, which expects a function parameter, as the error tells you. VTC as typo/resolved in a way unhelpful to future visitors. Commented Feb 22, 2020 at 19:52
  • @ggorlen - what about this - https://www.w3schools.com/jsref/jsref_findindex.asp Commented Feb 22, 2020 at 19:55
  • 1
    What about it? It says the same thing as above which is that you need to pass a function to findIndex. You could do this with styles.findIndex(e => e === a); but this is a more verbose and less efficient way to write styles.indexOf(a). Commented Feb 22, 2020 at 19:59

2 Answers 2

3

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
});
Sign up to request clarification or add additional context in comments.

2 Comments

what about this - https://www.w3schools.com/jsref/jsref_findindex.asp
see this link, explained very well: stackoverflow.com/questions/41443029/…
1

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

1 Comment

@qadenza Does this answer your question? Let me know if you need any help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.