如何判斷一個變量是不是數(shù)組?

2021-07-05

  • Array.isArray() 判斷,返回true,說明是數(shù)組
  • obj instanceof Array判斷,返回true。說明是數(shù)組
  • 使用Object.prototype.toString.call判斷,如果值是[object Array],說明是數(shù)組
  • 通過constructor來判斷,如果是數(shù)組,那么arr.constructor === Array(不準確,因為我們可以指定obj.constructor = Array)
function fn() {
    console.log(Array.isArray(arguments));   //false; 因為arguments是類數(shù)組,但不是數(shù)組
    console.log(Array.isArray([1,2,3,4]));   //true

    console.log(arguments instanceof Array); //fasle
    console.log([1,2,3,4] instanceof Array); //true

    console.log(Object.prototype.toString.call(arguments)); //[object Arguments]
    console.log(Object.prototype.toString.call([1,2,3,4])); //[object Array]

    console.log(arguments.constructor === Array); //false
    arguments.constructor = Array;
    console.log(arguments.constructor === Array); //true
    console.log(Array.isArray(arguments));        //false
}
fn(1,2,3,4);

typeof 注意以下

alert(typeof 1);                // 返回字符串"number" 
alert(typeof "1");              // 返回字符串"string" 
alert(typeof true);             // 返回字符串"boolean" 

alert(typeof {});               // 返回字符串"object" 
alert(typeof []);               // 返回字符串"object " 

alert(typeof function(){});     // 返回字符串"function" 

alert(typeof null);             // 返回字符串"object" 
alert(typeof undefined);        // 返回字符串"undefined"

typeof 和 instanceof 的區(qū)別?
兩者都可以用來判斷變量,typeof會返回基本類型

參考文章
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容