// 获取变量类型的几种方法
// 1. 使用 typeof 操作符
let str = "Hello";
let num = 123;
let obj = { key: "value" };
let arr = [1, 2, 3];
let func = function() {};
let und = undefined;
let nul = null;
console.log(typeof str); // "string"
console.log(typeof num); // "number"
console.log(typeof obj); // "object"
console.log(typeof arr); // "object" (数组也是对象)
console.log(typeof func); // "function"
console.log(typeof und); // "undefined"
console.log(typeof nul); // "object" (这是一个历史遗留问题)
// 2. 使用 Object.prototype.toString.call 方法
console.log(Object.prototype.toString.call(str)); // "[object String]"
console.log(Object.prototype.toString.call(num)); // "[object Number]"
console.log(Object.prototype.toString.call(obj)); // "[object Object]"
console.log(Object.prototype.toString.call(arr)); // "[object Array]"
console.log(Object.prototype.toString.call(func)); // "[object Function]"
console.log(Object.prototype.toString.call(und)); // "[object Undefined]"
console.log(Object.prototype.toString.call(nul)); // "[object Null]"
// 3. 自定义函数来判断类型
function getType(value) {
return Object.prototype.toString.call(value).slice(8, -1);
}
console.log(getType(str)); // "String"
console.log(getType(num)); // "Number"
console.log(getType(obj)); // "Object"
console.log(getType(arr)); // "Array"
console.log(getType(func)); // "Function"
console.log(getType(und)); // "Undefined"
console.log(getType(nul)); // "Null"
上一篇:js 取数组的值
下一篇:js array 遍历
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站