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