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

javascript - checking if input corresponds to 1 array value - Stack Overflow

programmeradmin1浏览0评论

I'm having an array:

var something = ["1","2","3","4"] ;

I'll ask the user in a prompt to pick a number. if it corresponds to any value in the array it triggers something.

My question is: How do i check if the input corresponds to any array value?

if(something === "input"){
    console.log("u picked a good number");
} 

Of course if statement i have now is incorrect, but how do i make it check every value in the array, and see if anything corresponds?

Would be awsome if someone could help me on this one! ;)

thxx!

I'm having an array:

var something = ["1","2","3","4"] ;

I'll ask the user in a prompt to pick a number. if it corresponds to any value in the array it triggers something.

My question is: How do i check if the input corresponds to any array value?

if(something === "input"){
    console.log("u picked a good number");
} 

Of course if statement i have now is incorrect, but how do i make it check every value in the array, and see if anything corresponds?

Would be awsome if someone could help me on this one! ;)

thxx!

Share asked Apr 11, 2013 at 8:24 KevinvhengstKevinvhengst 1,7024 gold badges27 silver badges40 bronze badges 2
  • 3 possible duplicate of Javascript: Determine whether an array contains a value - use indexOf() – Fabrizio Calderan Commented Apr 11, 2013 at 8:25
  • possible duplicate of array.contains(obj) in JavaScript – Ivaylo Strandjev Commented Apr 11, 2013 at 8:27
Add a ment  | 

1 Answer 1

Reset to default 9

Arrays have an indexOf method which returns the index at which the argument was found in the array, or -1 if it wasn't found:

if (something.indexOf(input) > -1) {
    // In the array!
}

Note that some older browsers don't support this method, but there is a polyfill in the MDN article linked to above.

发布评论

评论列表(0)

  1. 暂无评论