typeof与instanceof

  • 判断字符串类型可用typeOf,但判断数组,对象,正则,null时,返回的都是Object,所以可用instanceof来判断类型
<script>
	var str = 'Lee';
	alert(typeof str);//string
	var arr = [1,2,3];
	alert(typeof arr);//object
	alert(arr instanceof Array);//true
</script>
  • *注意:当类型为string时,用 instanceof 判断的话会为 false *
<script>
	var str = 'xu xiao dai';
	alert(str instanceof String);//false
	var strObj = new String('xu xiao dai');
	alert(strObj instanceof String);//true
</script>