找出变量是否在数组中? [英] Find out if a variable is in an array?

查看:74
本文介绍了找出变量是否在数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量:

var code = "de";

我有一个数组:

var countryList = ["de","fr","it","es"];

有人可以帮助我,因为我需要检查变量是否在countryList数组中 - 我的尝试在这里:

Could someone help me as I need to check to see if the variable is inside the countryList array - my attempt is here:

    if (code instanceof countryList) {
        alert('value is Array!');
    } 

    else {
        alert('Not an array');
    }

但是在运行时我在console.log中收到以下错误:

but I get the following error in console.log when it's run:


TypeError:无效'instanceof'操作数countryList

TypeError: invalid 'instanceof' operand countryList


推荐答案

jQuery有一个实用程序函数来查找元素是否存在于数组中

jQuery has a utility function to find whether an element exist in array or not

$.inArray(value, array)

它返回中的值的索引数组 -1 如果数组中不存在值。所以你的代码可以是这样的

It returns index of the value in array and -1 if value is not present in array. so your code can be like this

if( $.inArray(code, countryList) != -1){
     alert('value is Array!');
} else {
    alert('Not an array');
}

这篇关于找出变量是否在数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆