【问题标题】:Easier way to pass multiple parameters in a function with javascript使用javascript在函数中传递多个参数的更简单方法
【发布时间】:2020-10-10 17:36:42
【问题描述】:

这是一个判断参数是否为字符串的 JavaScript 函数

只是好奇是否有人可以简化此功能? 我不禁认为有,因为参数有很多相似之处

typeof x === "string"

有一种方法可以简化它。我问过我的老师,他们告诉我他们不知道。

function isString(string1, string2, string3) {
        if (typeof x === "string" && typeof y === "string" && typeof z === "string")
        console.log("Yes!" + x + " " + y + " " + z)
        else {
          console.log("Nope!")
        }
      }

      isString("String1", "String2", "String3")

我非常期待阅读您的回复!

谢谢 -乔

【问题讨论】:

  • 你的函数是否需要恰好三个字符串?有一些方法可以通过使用任意数量的字符串来使其更通用。
  • 应该是string1/string2/string3 而不是x/y/z
  • 我会使用带参数的 rest 参数,使用 args.every,并传递一个自定义函数来检查项目是否为字符串。
  • 你也可以发送一个字符串数组。

标签: javascript function dry simplify


【解决方案1】:

您可能正在寻找rest parametersarguments object,它们可以让您处理任意数量的参数,以及对它们进行循环(或为此使用a helper method):

function areStrings(...args) {
    if (args.every(x => typeof x === "string"))
        return "Yes!" + args.join(" ");
    else
        return "Nope!";
}

console.log(areStrings("String1", "String2", "String3"));
console.log(areStrings(5, "someString"));

【讨论】:

    【解决方案2】:

    您可以将参数作为数组 o 接收,并使用功能参数进行检查:

    function isString(...strings) {
      if (strings.every(s => typeof s === 'string'))
         console.log("They are string")
      else
         console.log("They are not string")
    }
    

    【讨论】:

    • 是的,我的错,我会改变答案
    【解决方案3】:

    如果要检查多个变量是否为字符串,可以使用这个函数:

    function isString(...args){
      for(var i = 0; i<args.length; i++){
        if(typeof args[i] !== 'string'){
          return false;
        }
      }
      return true;
    }
    

    您可以传递任意数量的参数,并且只有当所有参数都是字符串时,结果才会为真。

    例子:

    • isString(4) 返回false
    • isString("Hello World") 返回true
    • isString("I am a string", 3, true, "Hello") 返回false
    • isString("Hello World", "Welcome") 返回true

    【讨论】:

      猜你喜欢
      • 2013-02-10
      • 2017-11-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-01
      相关资源
      最近更新 更多