Javascript Checking an array for a specific number

I have a search for quite a lot of questions here, but havent found one that seems to be suitable for my account, so if you know that one of them refers to it.

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

I have something like this

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
}

but this will start the length of the array and ultimately check the last element of the array, and since the last element is not equal to 8, it will change the image to image2.

Now I can understand why this is happening, I just have no idea how to check if the array contains a specific number.

Thanks in advance.

+3
5

, , , :

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
}

.


:

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


P.S. Array , .

+8

, :

for(x=0;x<=Array.length;x++)
{
    if(Array[x]==8) {
        //change picture.src to srcpicture1
        break;
    }
}
+3

, , , .

0

, - , , ( , ). , "if (num in arr)".

0

Source: https://habr.com/ru/post/1723856/


All Articles