Javascript检查数组是否存在特定号码 [英] Javascript Checking array for presence of a specific number

查看:96
本文介绍了Javascript检查数组是否存在特定号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里搜索了很多问题,但还没找到一个我认为适合我的账单,所以如果你知道一个请链接到它。

I have search through quite a lot of questions here, but havent found one that i think fits my bill, so if you know of one please link to it.

我有一个数组,我想搜索一个特定的数字,如果该数字在数组中,我然后想要采取行动,如果没有,那么另一个行动。

I have an array that i want to search through for a specific number and if that number is in the array, i then want to take an action and if not then another action.

我有类似的东西

var Array = ["1","8","17","14","11","20","2","6"];

for(x=0;x<=Array.length;x++)
{
    if(Array[x]==8)
        then change picture.src to srcpicture1
    else
        then change picture.src to srcpicture2
}

但这会运行数组的长度并最终检查数组的最后一个元素,因为最后一个元素不是8,那么它会将图片更改为picture2。

but this will run the lenght of the array and end up checking the last element of the array and since the last element is not 8 then it will change the picture to picture2.

现在我可以看到为什么会发生这种情况,我对如何检查数组是否包含特定数字没有任何想法。

Now i can see why this happens, i just dont have any ideas as to how to go about checking if an array contains a specific number.

谢谢提前。

推荐答案

你能做的就是自己写一个函数来检查一个元素是否属于一个数组:

What you can do is write yourself a function to check if an element belongs to an array:

function inArray(array, value) {
    for (var i = 0; i < array.length; i++) {
        if (array[i] == value) return true;
    }
    return false;
}

刚刚做:

var arr = ["1","8","17","14","11","20","2","6"];
if (inArray(arr, 8)) {
    // change picture.src to srcpicture1
} else {
    // change picture.src to srcpicture2
}

这对我来说更具可读性。

It's a lot more readable to me.

对于额外的积分,您可以将函数添加到数组原型中,如下所示:

For extra points you can add the function to the array prototype like so:

Array.prototype.has = function (value) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] === value) return true;
    }
    return false;
};

然后电话会是

if (arr.has(8)) // ...

进一步推动这一点,你可以在数组上检查 indexOf()方法并使用它 - 如果不是 - 用上面的代码替换它。

Pushing this even further, you can check for indexOf() method on array and use it - if not - replace it with the code above.

PS尽量不要使用 Array 作为变量名,因为它是为实际数组类型保留的。

P.S. Try not to use Array for a variable name, since it's reserved for the actual array type.

这篇关于Javascript检查数组是否存在特定号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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