检查 jQuery 中的函数 return 是否为假

Check if function return false in jQuery

我在尝试检查函数 return 是否为假时遇到了麻烦。

我正在编写一个脚本,当用户 select 在输入表单字段中上传图片文件时。

所以 html 形式如下:

<form enctype="multipart/form-data" id="upload-form" role="form">
<input type="hidden" id="register-id" name="id" value="">
<div class="row">
    <div class="col-md-12">
        <div class="form-group">
            <label>Select image</label>
            <div class="custom-file">
                <input type="file" name="filedata" class="custom-file-input" id="picture" accept="image/*">
                <label class="custom-file-label" for="picture">Choose file</label>
            </div>
        </div>
        <div class="progress mb-2 progress-sm">
            <div id="file-progress-bar" class="progress-bar" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
        </div>
    </div>
</div>
</form>

在输入更改时获取文件的javascript代码如下,代码应该开始一些文件检查

$('#picture').on('change', function() {
    let picture = this.files[0];

    if(!checkFile(picture)) {
        alert("Check file not passed");
        return false;
    }
});

问题是:脚本停止执行并显示警告消息 "Check file not passed",即使被调用的 checkFile 函数没有 return 失败,因为文件通过了所有检查。 怎么了?非常感谢。

checkFile 函数下方

function checkFile(picture) {
    let imagetype = picture.type;
    console.log('Picture type ' + imagetype);
    let match= ["image/jpeg","image/png","image/jpg"];
    if(!((imagetype==match[0]) || (imagetype==match[1]) || (imagetype==match[2])))
    {
        console.log('Matching picture type failed');
        return false;
    }

    let reg=/(.jpg|.gif|.png)$/;
    console.log('Picture name is ' + picture.name);
    if (!reg.test(picture.name)) {
        console.log('Check picture name failed');
        return false;
    }
    console.log('Picture size is ' + picture.size);
    if (picture.size > 204800) {
        console.log('Check picture size failed');
        return false;
    }
}

有没有更好的策略在上传前检查文件?

非常感谢任何反馈

只需 return true 在函数的末尾。如果您不会 return 函数中的任何内容,它将 return undefined 这是一个虚假值。

function checkFile(picture) {
  let imagetype = picture.type;

  // ... rest of the code

  if (picture.size > 204800) {
    console.log('Check picture size failed');
    return false;
  }
  return true;
}

或者您可以更改条件以与 false

完全匹配
if(checkFile(picture) === false) {
  alert("Check file not passed");
  return false;
}

当所有检查都通过后,您忘记了 return true。

function checkFile(picture) {
    [...previousLines]

    return true;
}