简体   繁体   中英

return TRUE or FALSE from a function

Here i have a function .It accepts an array of object and a specific value.The array is iterated using a forEach method to ensure the provided value is already existed in any of the objects in the array.If found it returns FALSE ,or it should return true.But although it returns FALSE ,the rest of the code alse gets executed results in returning TRUE all the time.How i can return only FALSE/TRUE

   if(find_value_in_obj(all_selected,current.value)){
        all_selected.push({select_elem:current,value:current.value});
        console.log(all_selected);
    }else{

        alert("you already selected the value");   
    }

  function find_value_in_obj(arr_obj,value){

        arr_obj.forEach(function(elem,index,array){

            if(elem.value == value){
                console.log('found it ');
                return false;
            }
        });
        console.log("i am her"); // though value already exists and should returned ,it gets executed results in returning TRUE instead

        return true;
    }

forEach cannot be broken in middle of its iteration like a regular for loop. Use a regular for loop instead. Or, if you are using ES6 then you could achieve the same thing by using .find() .

function find_value_in_obj(arr_obj,value){
   return !!!arr_obj.find(itm => itm == value);
}

As felix suggested, you could make use of Array.prototype.some also.

function find_value_in_obj(arr_obj,value){
   return !arr_obj.some(itm => itm == value);
}

forEach iterates over all values. You should be using .some() .

And since using some is just a one-liner, you don't actually need to create a helper for it, for example (from MDN):

 console.log([2, 5, 8, 1, 4].some(elem => elem > 10)); // false console.log([12, 5, 8, 1, 4].some(elem => elem > 10)); // true 

You can also try using filter, which is more appropriate and clean.

   if(find_value_in_obj(all_selected,current.value)){
    all_selected.push({select_elem:current,value:current.value});
    console.log(all_selected);
}else{

    alert("you already selected the value");   
}

function find_value_in_obj(arr_obj,value){

    var resultArray = arr_obj.filter(function(elem,index,array){
        return elem.value == value;
    });

    if(resultArray.length > 0){
       return false;
    }
    console.log("i am her"); // though value already exists and should returned ,it gets executed results in returning TRUE instead

    return true;
}

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