I have been using Array.indexOf
in the Google Chrome console, I tried these codes
[1,2,3].indexOf(3);
[1,2,"3"].indexOf("3");
They all returned 2, but when I tried these codes
[1,2,"3"].indexOf(3);
[1,2,3].indexOf("3");
They all returned -1. I want it also return 2, how could I do that? Thanks for your help, time, and effort!
expanding on guest271314's post: cast both of the values to a string. This will also work for numbers and strings
val = true
console.log([1,2,"true"].findIndex(item => String(item) === String(val)))
You can use Array.prototype.findIndex()
, ==
operator
var n = 3;
console.log(
[1,2,3].findIndex(el => el == n)
, [1,2,"3"].findIndex(el => el == n)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With