【问题标题】:what is the shortest way to check for typeof any type?检查任何类型的 typeof 的最短方法是什么?
【发布时间】:2019-08-20 10:43:19
【问题描述】:

我今天发现这个是为了检查某个东西是否是布尔值:

代替:

typeof a === 'boolean' && //do sth

你可以使用:

a === !!a && //do sth

还有其他类似的方法来检查typeof string/number/obj/arr等吗?

我不是在寻找最佳实践,而是在寻找聪明的方法来进行“类型检查”。

【问题讨论】:

  • 你到底为什么要重新发明typeof
  • 最聪明的方法是编写惯用的、被广泛理解和预期的代码。但我想这取决于你对理智的定义。
  • @IngoBürk - 或者聪明。

标签: javascript


【解决方案1】:

一个非常相似的概念适用于所有基本类型,但涉及函数调用和可能比布尔示例更多的工作:

// String
a === String(a)

// Number
n === +n  // **FAILS** if `a` is `NaN` (which is `typeof "number"`)
Object.is(n, +n) // Works even if it is, but 0 and -0 are considered different

// Object (including arrays)
o === Object(o)

最后一个有效,因为Object 返回你调用它的对象,如果你用一个对象调用它(它不会创建一个新对象)。


我知道你说过你对技巧感兴趣,而不是最佳实践,但是......一般来说,我不会做上述事情。如果我关心类型但不知道它是什么,我会使用 typeof,如果我想要特定的目标类型但不知道输入是什么类型,我会使用转换。

【讨论】:

  • 如果我看到Object.is(n, +n) 出现在任何更不重要的代码中,就会有咖啡杯飞扬。
  • @PaulStenne - 与您同在。 :-D
【解决方案2】:

javascript 中的类型并不那么简单,但this 是您的绝佳指南!

在 Javascript 中检查类型是一团糟。

类型运算符

一开始有typeof。这个方便的运算符为您提供 Javascript 值的“类型”:

typeof 3 // "number" 
typeof "abc" // "string"
 typeof {} // "object"
 typeof true // "boolean" 
typeof undefined // "undefined" 
typeof function(){} // "function" 

一切都很好,直到

typeof [] // "object" 

嗯?数组的类型是对象?我想是的,如果你想得到 关于它的技术,但仍然是……

typeof null // "object" 

好吧,那就错了!

instanceof 运算符

instanceof 操作符告诉你一个对象是否 是某种类型的实例。所谓“型”是 构造函数。例如

function Animal(){}
    var a = new Animal()
    a instanceof Animal // true

instanceof的跨窗口问题

原来instanceof还有一个问题。它崩溃时 您尝试测试来自另一个窗口的对象。你懂的?这 为每个创建的,或弹出窗口 你创造。

   var iframe = document.createElement('iframe')
    document.body.appendChild(iframe)
    var iWindow = iframe.contentWindow // get a reference to the window object of the iframe
    iWindow.document.write('<script>var arr = [1, 2, 3]</script>') // create an array var in iframe's window
    iWindow.arr // [1, 2, 3]
    iWindow.arr instanceof Array // false

鸭式打字

因为 typeof 和 instanceof 都不能令人满意,所以很多人使用 鸭子打字。这意味着检查行为:如果它看起来像鸭子 和鸭子一样嘎嘎叫,那么就我而言,它是一只鸭子。 很确定我引用错了……哦,好吧。

因此,使用鸭子类型,isArray 检查可能看起来像

// source: http://forums.devshed.com/javascript-development-115/javascript-test-whether-a-variable-is-array-or-not-33051.html
function isArray(obj){
    return (typeof(obj.length)=="undefined") ?
        false:true;
}

Object.prototype.toString 方法

事实证明,您可以通过以下方式获取有关对象的类型信息 使用 Object.prototype.toString 方法。

Object.prototype.toString.call(3) // "[object Number]"
Object.prototype.toString.call([1, 2, 3]) // "[object Array]"
Object.prototype.toString.call({}) // "[object Object]"

Function.prototype.toString 方法

另一种测试类型信息的方法是使用 Function.prototype.toString 方法。

Function.prototype.toString.call((3).constructor)
// "function Number() {
//    [native code]
// }"

DOM 元素和宿主对象

到目前为止,我还没有提到 DOM 元素和宿主的类型检查 对象。那是因为它很难。除了打鸭子, 上述方法均不适用于所有浏览器。如果你 掉IE7及以下,但是,你实际上可以得到一些东西 去工作。下面的输出是使用 Tutti 创建的

var div = document.createElement('div')
typeof div
Safari 5.0 => object
Firefox 3.6 => object
IE 7.0 => object
IE 8.0 => object
Opera 11.01 => object
div instanceof Element
Safari 5.0 => true
Firefox 3.6 => true
IE 7.0 => Error: 'Element' is undefined
IE 8.0 => true
Opera 11.01 => true
div instanceof HTMLDivElement
Safari 5.0 => true
Firefox 3.6 => true
IE 8.0 => true
IE 7.0 => Error: 'HTMLDivElement' is undefined
Opera 11.01 => true

http://tobyho.com/2011/01/28/checking-types-in-javascript/

【讨论】:

    【解决方案3】:

    干净的方法

    你不能干净利落地做。 Javascript 有一些怪癖,我看到这些怪癖几乎总是让人们望而却步,即使是最有经验的人。很多时候你会得到非常丑陋的,不是人类可读的条件语句:

    if (
        typeof foo !== 'string'
        || (typeof foo !== 'number'
        || (typeof foo === 'number' && !isNaN(chk)))
        || !Array.isArray(chk)
    ) {
    
        throw Error("Not valid, but I don't know why.")
    }
    

    别无他法,就用一个很轻量级的库

    您应该考虑使用像Issable 这样的非常小的库。解决所有问题:

    let integer = 10
    let array = []
    is(integer).number() // returns true
    is(array).number() // throws error
    

    如果你养成习惯,你的代码会更强大。 Typescript 解决了部分问题,但在运行时不起作用,这也很重要。

    function test (string, boolean) {
        // any of these below will throw errors to protect you
        is(string).string()
        is(boolean).boolean()
        // continue with your code.
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-27
      • 1970-01-01
      相关资源
      最近更新 更多