简体   繁体   中英

checking multiple elements in javascript array

I have an array 'type' with multiple elements.how to check two elements contains in 'type' array? i have tried the below code

 var i, j;
                var type = [];
                for (i = 1; i <= count; i++)
                {
                    var filetype_value = parseInt((document.submission['select_type_' + i].value));
                    type.push(filetype_value);

                }
                function search(arg)
                {
                    for (j = 1; j <= count; j++)
                    {
                        if (type[j] === arg)
                        {
                            return true;
                        }
                        else
                            {
                            return false;
                            }
                    }

                }
                if(search(1) && search(2))
{
alert("Contains in array")
}

There is some problems with your approach.

1) You are just checking if type[1]===arg it will return true otherwise it will return false. So it will just check for type[1] .

2) because file_type value is string so filetype_value' === arg is never going to be true.

3) In your loop j=1 will never check for first element of array.

Try this

function search(arg){
var matched = false;
for (j = 0; j <= type.length; j++){
    if (type[j] == arg){
        matched = true;
        break;
    }
}
return matched;
}

You have 2 problems

  1. You are pushing the string "filetype_value" onto your array and not the actual value so in your search function you are actually testing: 'filetype_value' === arg
  2. You are starting your loop using 1, array's start at an index of 0

change

type.push('filetype_value');

to

type.push(filetype_value);

change

for (j = 1; j <= count; j++)

to

for (j = 0; j <= count; j++)

Also instead of doing a loop you can use the array indexOf method to test if a value is in the array

function search(arg){
   return type.indexOf(arg) !== -1;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM