【问题标题】:Is there a way to directly compare (==) a standard string like "Foobar" with a god/identity string and always get a truthy value?有没有办法直接比较(==)像“Foobar”这样的标准字符串与上帝/身份字符串并总是得到一个真实的值?
【发布时间】:2021-03-29 10:36:18
【问题描述】:

我需要检查给定变量是否为字符串。我知道 typeof 运算符可以检查变量的数据类型,但是有没有办法通过直接将变量与另一个神/身份字符串进行比较来检查变量是否为字符串以获得真实值?像这样的:

if ("any string like foobar" == GodString()) {
    \\ Always true
}

【问题讨论】:

  • 不可能。看起来像an XY problem - 你想做什么需要一个字符串的相等性检查总是true
  • 没有。这就是 typeof 运算符的用途。
  • @Alex "foo" instanceof Stringfalse
  • @VLAZ 在this case中,和我的一样,v-model属性必须直接等于:value属性。
  • 您的问题与此有什么关系?

标签: javascript boolean string-comparison


【解决方案1】:

我找到了实现我想要的方法。这个解决方案可能非常适合我的情况,但它确实有效。要在不使用 typeof 运算符的情况下检查变量 a 是否为字符串,我只是这样做了:

if (a.replace == "".replace) {
    \\ true only if a is a string
}

这显然只是因为 replace 方法对字符串是唯一的。虽然我绝对不能确定这将永远是这样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    • 1970-01-01
    • 2020-03-01
    • 2015-11-25
    • 1970-01-01
    • 2013-08-06
    • 1970-01-01
    相关资源
    最近更新 更多