首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

js取传入数据类型

在JavaScript中,可以使用typeof操作符来获取传入数据的类型。typeof操作符返回一个表示未经计算的操作数类型的字符串。

以下是一些使用typeof操作符的示例:

代码语言:txt
复制
console.log(typeof 42); // "number"
console.log(typeof 'blubber'); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object"(这是一个历史遗留问题)
console.log(typeof {}); // "object"
console.log(typeof []); // "object"
console.log(typeof function() {}); // "function"

需要注意的是,typeof对于数组和null值会返回"object",这可能会导致一些混淆。如果你需要更精确地检测数据类型,可以使用Object.prototype.toString.call()方法:

代码语言:txt
复制
console.log(Object.prototype.toString.call([])); // "[object Array]"
console.log(Object.prototype.toString.call(null)); // "[object Null]"
console.log(Object.prototype.toString.call({})); // "[object Object]"

此外,还可以使用一些自定义的类型检测函数来更准确地判断数据类型,例如:

代码语言:txt
复制
function isArray(value) {
  return Array.isArray(value);
}

function isNull(value) {
  return value === null;
}

console.log(isArray([])); // true
console.log(isNull(null)); // true

总之,在JavaScript中获取传入数据的类型可以使用typeof操作符,但对于一些特殊类型(如数组和null),可能需要使用其他方法来进行更精确的判断。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券