javascript - 当 x 可能有多种类型时,如何知道 x 是什么

标签 javascript

如何知道js中的x是什么?

有时我必须编写一个带有多种类型参数的函数。例如测试(x);在运行代码之前我需要知道 x 是什么。

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<div class="hello">hello</div>
<script type="text/javascript">

    // the x var will be random 1 of 4 bellow , how to know what is it ?
    var x = $('.hello')[0];
    var x = ['1','2'];
    var x = {'name':'jimmy'};
    var x = 'hello';

    if(???){
        // alert x is a html node
    }
    if(???){
        // alert x is a js arr
    }
    if(???){
        // alert x is a js obj
    }
    if(???){
        // alert x is a js str
}

</script>

最佳答案

if(typeof x === 'string'){
    // string
} else {
    if(x instanceof Array){
        // array
    } else if(x.nodeType){
        // element
    } else if(typeof x === 'object') {
        // object
    }
}

Fiddle

关于javascript - 当 x 可能有多种类型时,如何知道 x 是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20985850/

相关文章:

javascript - 动态创建元素上的 Angular 模块

javascript - 如何禁用点击选定的数据表jquery?

javascript - 无法通过 php 和 ajax 从数据库中检索下拉菜单的详细信息

javascript - localStorage 和 jQuery(没有工作的 css)

Javascript - 试图延迟遍历 for 循环

javascript - Angular 服务的返回 promise

Javascript:将对象插入集合

javascript - WebAssembly:类型错误:WebAssembly 实例化:必须存在导入参数

javascript - Node.js 在哪里存储缓冲区?

javascript - 如何更改 Recharts 中每个条的颜色?