【问题标题】:How can I check if a parameter is AND is not a typeof string?如何检查参数是否 AND 不是 typeof 字符串?
【发布时间】:2021-04-13 14:59:55
【问题描述】:

我正在寻找一种算法,但遇到了一些问题。在这里,我设法使用typeof 检查它是否是一个字符串,但我还需要检查它是否不是一个字符串,我需要帮助。

function isString(a, b, c) {
  if (typeof a, typeof b, typeof c === 'string') {
    return 'all parameters are strings';
  } else {
    return 'one of the parameters is not a strings';
  }
}

【问题讨论】:

  • 使用if(typeof someVariable != "string") { ... }
  • 如你所知,typeof a === 'string' && typeof b === 'string' && typeof c === 'string'
  • typeof a, typeof b, typeof c === 'string' 不是有效的 JS
  • 还有一件事:如果您试图验证a、b 和c 的all 是否是字符串,那么这不是执行此操作的方法。你应该使用if(typeof a === "string" && typeof b === "string" && typeof c === "string") { ... }

标签: javascript string typeof


【解决方案1】:

你的 JS 无效。

如果您只想进行一次测试,可以在将参数传播到数组后执行every

const isString = function(a, b, c) {
  return [...arguments].every(arg => typeof arg === "string") ? 'all parameters are strings' : 'one of the parameters is not a string'
};

console.log(isString("", "", ""))
console.log(isString("", 9, ""))

【讨论】:

    猜你喜欢
    • 2021-09-27
    • 2011-05-23
    • 1970-01-01
    • 2023-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多