js中typeof语法有什么作用

2025年02月02日 建站教程

typeof是用来求值结果作为其操作数的类型结果字符串,属于一元运算符。还可以替代语法是在括号中使用操作数,这对于检查JavaScript表达式返回值的类型非常有用。下面web建站小编给大家详细介绍一下具体使用方法!

基本用法:

typeof "web"; // 'string'
typeof 22; // 'number'
typeof NaN; // 'number'
typeof Infinity; // 'number'
typeof true; // 'boolean'
typeof false; // 'boolean'
typeof [1, 2]; // 'object'
typeof {age: 22}; // 'object'
typeof null; // 'object'
typeof undefined; // 'undefined' 
typeof String; // 'function'
typeof Boolean; // 'function' 
typeof Number; // 'function'
typeof Object; // 'function'
typeof Function; // 'function'
typeof person; // 'function'

检测值是否存在在不同环境:

if (typeof window !== 'undefined') {
 // 浏览器
};
if (typeof process !== 'undefined') {
 // Node.js
}
if (typeof $ !== 'undefined') {
 // jQuery 
}

本文链接:http://so.lmcjl.com/news/22534/

展开阅读全文
相关内容