简体   繁体   中英

Easier way to pass multiple parameters in a function with javascript

This is a JavaScript function that determines if arguments are strings

just curious if anyone has a way to simplify this function? I can't help but think there is since there are so many similarities in the parameters

typeof x === "string"

that there is a way to simplify it. I asked my teachers and they told me they were unaware of any.

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")

I really look forward to reading your responses!

Thanks -Joe

You might be looking for rest parameters or the arguments object that let you handle an arbitrary amount of arguments, together with looping over them (or using a helper method for that):

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"));

you can receive your params as an array o, and the use functional parameter to check:

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

If you want to check if multiple variables are strings, you can use this function:

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

You can pass as much parameters as you want and the result will be only true if all parameters are strings.

Example:

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

Clear answer, simple effective. I come to propose another way of doing things. Arrow function + ternary. More verbose but condense. (I didn't know every cool:))

var resultAmeliored = (...args) => 'Var: '+args.map(val => val+' is '+typeof val).join(', ');

var areStrings = (...args)=>args.every(s => typeof s === 'string')?true:false;

console.log(areStrings("String1", "String2", "String3"));
//true
console.log(resultAmeliored(5, "someString"));
//"Var: 5 is number, someString is string"

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