JavaScript中typeof正确使用

首先要明确的是  在JS中使用typeof不能正确的判断是数组Array还是对象Object

例:var arr = [ ] 

       typeof(arr)===“object”  //true

       结果返回的是true  但明显arr是一个数组

正确判断数组的方法:

(1)使用isarray方法

          var testArray = new array():

          testArray[0] = "testOne";

          testArray[1] = "testTwo";

          testArray[2] = "testThree";

          testArray[3] = "testFour";

          if(Array.isArray){

                 if(Array.isArray(testArray)){

                       document.write("这是一个数组");

                 }

}

(2)使用instanceof操作符

          var testArray = new array():

          testArray[0] = "testOne";

          testArray[1] = "testTwo";

          testArray[2] = "testThree";

          testArray[3] = "testFour";

          if(testArray instanceof Array){

                document.write("这是一个数组");

}

       

猜你喜欢

转载自www.cnblogs.com/zhuyan-dailycheck/p/9811522.html
今日推荐