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

qadenza
  • 9,025
  • 18
  • 73
  • 126
  • 1
    I think you meant `indexOf` rather than `findIndex`, which [expects a function parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex), as the error tells you. VTC as typo/resolved in a way unhelpful to future visitors. – ggorlen Feb 22 '20 at 19:52
  • @ggorlen - what about this - `https://www.w3schools.com/jsref/jsref_findindex.asp` – qadenza Feb 22 '20 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)`. – ggorlen Feb 22 '20 at 19:59

2 Answers2

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
});
harsh_apache
  • 433
  • 4
  • 10
  • 1
    what about this - `https://www.w3schools.com/jsref/jsref_findindex.asp` – qadenza Feb 22 '20 at 19:55
  • see this link, explained very well: https://stackoverflow.com/questions/41443029/difference-between-indexof-and-findindex-function-of-array – harsh_apache Feb 22 '20 at 20:02
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);
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56