在 JavaScript 里 使用 typeof 来判断数据类型,只能区分基本类型,即 “ number ” , “ string ” , “ undefined ” , “ boolean ” , “ object ” ,"function"六种
typeof ''; // string 有效
typeof 1; // number 有效
typeof true; // boolean 有效
typeof undefined; // undefined 有效
typeof null; // object 无效
typeof [] ; // object 无效
typeof new Function(); // function 有效
typeof new Date(); // object 无效
typeof new RegExp(); // object 无效
引用类型判断
区别对象、数组、函数可以使用Object.prototype.toString.call 方法。判断某个对象值属于哪种内置类型。
console.log(Object.prototype.toString.call(123)) // [object Number]
console.log(Object.prototype.toString.call('123')) // [object String]
console.log(Object.prototype.toString.call(undefined)) // [object Undefined]
console.log(Object.prototype.toString.call(true)) // [object Boolean]
console.log(Object.prototype.toString.call({})) // [object Object]
console.log(Object.prototype.toString.call([])) // [object Array]
console.log(Object.prototype.toString.call(function(){})) // [object Function]
console.log(Object.prototype.toString.call(this)); // [object Window]
isArray() 方法用于判断一个对象是否为数组。
如果对象是数组返回 true,否则返回 false。
本文介绍了在JavaScript中如何使用typeof操作符来判断基本数据类型,包括number、string、boolean、undefined、object和function。然而,typeof对于引用类型如数组、函数和特定对象的判断存在局限。为准确识别这些类型,可以利用Object.prototype.toString.call方法,它能返回对象的内部类字符串,从而区分对象、数组、函数等。此外,还提到了isArray()方法用于检测数组。
1278

被折叠的 条评论
为什么被折叠?



