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!
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!
Share Improve this question edited May 25, 2017 at 5:40 Flostin 1195 bronze badges asked May 25, 2017 at 4:53 HzzHzz 1,9382 gold badges18 silver badges25 bronze badges 4- change [1,2,"3"].indexOf("3"); and [1,2,3].indexOf(3); – Edison Augusthy Commented May 25, 2017 at 4:56
-
probably just turn everything into a string then inside
indexOf
– A. L Commented May 25, 2017 at 5:01 - Why are you storing different datatypes in the array? Can't you make sure that you convert everything to numbers first? – Barmar Commented May 25, 2017 at 5:08
- Good Idea, @A.Lau . Thanks A. Lau and Edison – Hzz Commented May 25, 2017 at 5:09
2 Answers
Reset to default 7expanding 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)
)