在JavaScript中,我们可以使用以下方式来判断一个值的数据类型:
typeof "hello"将返回"string",而typeof 123将返回"number"。[] instanceof Array将返回true,因为空数组是Array类的一个实例。Object.prototype.toString.call([])将返回"[object Array]"。[].constructor === Array将返回true。下面是具体的代码演示:
// 判断基本数据类型
console.log(typeof "hello"); // string
console.log(typeof 123); // number
console.log(typeof true); // boolean
console.log(typeof undefined); // undefined
console.log(typeof null); // object
console.log(typeof Symbol()); // symbol
console.log(typeof BigInt(123)); // bigint
// 判断对象类型
console.log([] instanceof Array); // true
console.log(new Date() instanceof Date); // true
console.log(/foo/ instanceof RegExp); // true
// 使用toString判断
console.log(Object.prototype.toString.call([])); // [object Array]
console.log(Object.prototype.toString.call(new Date())); // [object Date]
// 使用constructor属性判断
console.log([].constructor === Array); // true
console.log(new Date().constructor === Date); // true总体来说,不同的方式在某些情况下可能会有所差异,我们需要根据场景选择合适的方式。