如何检查 JavaScript 中的 3 个参数是否为空或未定义?

在函数内部插入一个用于检查空参数和未定义参数的 if 语句是否更好?或者我应该为空和未定义的参数检查创建另一个函数?我对差异感到困惑。


我有这段代码,但我不确定是否在函数内部使用 if 语句,因为我真的不知道把它放在哪里,或者我应该放弃并在它下面创建另一个函数?


function noManagement(code, digit, input) {


        var inputArr = input.split("");


    let result = null;

        for (var i = 0; i < digit; i++) {

        inputArr.unshift(0);


            if (inputArr.length === digit) {

        result = code + inputArr.join("");

        }

    }

    return result;

}

如果我为 null 和 undefined 检查插入一个 if 语句,我应该把 return 语句放在哪里?


我还有另一个函数来调用这个函数


function showOutput(){

       var input=document.getElementById("search-input").value;

       var dislay=document.getElementById("search-output");

       dislay.value=noManagement("A", 9, input);

    }


MMTTMM
浏览 153回答 2
2回答

梵蒂冈之花

简单的方法如下:function noManagement(code, digit, input) {&nbsp; if (arguments.length < 3) throw "Not enough arguments";&nbsp; for (var i = 0; i < 3; i++) {&nbsp; &nbsp; if (arguments[i] == null) throw "Bad argument";&nbsp; }&nbsp; var inputArr = input.split("");&nbsp; let result = null;&nbsp; for (var i = 0; i < digit; i++) {&nbsp; &nbsp; inputArr.unshift(0);&nbsp; &nbsp; if (inputArr.length === digit) {&nbsp; &nbsp; &nbsp; result = code + inputArr.join("");&nbsp; &nbsp; }&nbsp; }&nbsp; return result;}虽然,因为您的参数应该是字符串、数字、字符串function noManagement(code, digit, input) {&nbsp; if (typeof code !== 'string') throw "first argument should be String";&nbsp; if (typeof digit !== 'number') throw "second argument should be Number";&nbsp; if (typeof input !== 'string') throw "third argument should be String";&nbsp; var inputArr = input.split("");&nbsp; let result = null;&nbsp; for (var i = 0; i < digit; i++) {&nbsp; &nbsp; inputArr.unshift(0);&nbsp; &nbsp; if (inputArr.length === digit) {&nbsp; &nbsp; &nbsp; result = code + inputArr.join("");&nbsp; &nbsp; }&nbsp; }&nbsp; return result;}

忽然笑

这是一个简单的添加,将检查未定义。如果未提供三个中的任何一个,它将停止执行该函数function noManagement(code, digit, input) {&nbsp; &nbsp; if (!code) throw new Error("code is undefined");&nbsp; &nbsp; if (!digit) throw new Error("digit is undefined");&nbsp; &nbsp; if (!input) throw new Error("input is undefined");&nbsp; &nbsp; var inputArr = input.split("");&nbsp; &nbsp; let result = null;&nbsp; &nbsp; &nbsp; &nbsp; for (var i = 0; i < digit; i++) {&nbsp; &nbsp; &nbsp; &nbsp; inputArr.unshift(0);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (inputArr.length === digit) {&nbsp; &nbsp; &nbsp; &nbsp; result = code + inputArr.join("");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return result;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript