最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Array.indexOf insensitive data type - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 7

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

发布评论

评论列表(0)

  1. 暂无评论