简体   繁体   中英

function always returning false

Fairly new to Javascript, could anybody tell me why this simple array loop / string comparison function always returns false? They're both of type string and the data is the same, the loop should absolutely return true. Possible syntax error? Also is there an easier way of running this check.

function imageDuplicate(fileName)
{
    $.each(previewImagesArray, function(index)
    {
        if(previewImagesArray[index].name == fileName)
            return true;
    });
    return false
}

Thanks in advance.

You are returning true from the the anonymous inner function, not from imageDuplicate , instead use a flag variable as shown below

function imageDuplicate(fileName) {
    var valid = false;
    $.each(previewImagesArray, function (index) {
        if (previewImagesArray[index].name == fileName) {
            valid = true;
            //to stop the iteration
            return false
        }
    });
    return valid
}

How about this instead:

function imageDuplicate(fileName)
{
   return  previewImagesArray.some(function(item)
    {
        return item.name === fileName;
    });
}

Important: this will work on IE9+ if you need this to run in older version of IE please follow the polyfill instructions here .

Other post samples:

javascript find an object with specific properties in an array

As mentioned in the comment returning from each loop, doesn't return from function.

Try something like this

function imageDuplicate(fileName)
{
    var isDuplicate = false;
    $.each(previewImagesArray, function(index)
    {
        if(previewImagesArray[index].name == fileName){
            isDuplicate = true;
            return false; //exit from each loop
       }
    });
    return isDuplicate; 
}

The code inside function(index) is a separate function, nested inside imageDuplicate . The return value of that function would be processed by .each() as it sees fit.

As such, the only statement which returns from your outer function is your return false .

As other answers are illustrating in code, you can declare a variable in the scope of imageDuplicate and have the inner function access and modify that value in order to get the effect you're wanting.

one tweak would be to use the value directly

    $.each(previewImagesArray, function (index, value) {
        if (value.name == fileName) {
            ...
        }
    });

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