检查类型是日常编码和技术面试中 javascript 的常见做法。
您可以在 github 上找到这篇文章中的所有代码。
在 javascript 中,除 object 之外的所有类型都定义直接在语言最低级别表示的不可变值。我们将这些类型的值称为原始值。
有 7 个原始值:
立即学习“Java免费学习笔记(深入)”;
除 null 之外的所有原始类型都可以通过 typeof 运算符进行测试。 typeof null 返回“object”,因此必须使用 === null 来测试 null。
因此,我们得到了第一种类型的效用函数。
function isboolean(value) { return typeof value === 'boolean'; } function isstring(value) { return typeof value === 'string'; } function isnumber(value) { return typeof value === 'number'; } function issymbol(value) { return typeof value === 'symbol'; } function isbigint(value) { return typeof value === 'bigint'; } function isundefined(value) { return typeof value === 'undefined'; } function isnull(value) { return value === null; } // usage example console.log(issymbol(symbol('test'))); // => true console.log(isnull(null)); // => true console.log(isundefined(undefined)); // => true console.log(isnumber(1)); // => true console.log(isstring('')); // => true console.log(isboolean(true)); // => true console.log(isbigint(9007199254740991n)); // => true
所有不是原始类型的东西都是 javascript 中的对象。这包括:
这是数组、函数、对象的第二个实用函数。
function isarray(value) { return array.isarray(value); } function isfunction(value) { return typeof value === 'function'; } function isobject(value) { // for null and undefined if (value == null) { return false; } return typeof value === 'object'; } function isplainobject(value) { // for null and undefined if (value == null) { return false; } const prototype = object.getprototypeof(value); return prototype === object.prototype || prototype === null; } // usage example console.log(isarray(new array())); // => true console.log(isobject(object(null))); // => true console.log(isfunction(object.prototype.tostring)); // => true console.log(isplainobject(object.create(null))); // => true
javascript 中有多种检查类型的方法,包括:
object.prototype.tostring.call() 是 javascript 中最可靠的类型检查方法。
我们可以通过以下方式提取类型:
function getType(value) { const type = typeof value; if (type !== 'object') { return type; } return Object.prototype.toString .call(value) .slice(8, -1) .toLowerCase(); } // Usage example console.log(getType(1)); // => number console.log(getType('')); // => string console.log(getType({})); // => object console.log(getType(null)); // => null console.log(getType(undefined)); // => undefined console.log(getType(Symbol())); // => symbol console.log(getType(BigInt(1234567890123456789012345))); // => bigint console.log(getType(function () {})); // => function console.log(getType(new Date())); // => date console.log(getType(new Map())); // => map console.log(getType(new Set())); // => set console.log(getType(new RegExp("cat", "i"))); // => regex
以上就是类型实用程序 - JavaScript 挑战的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号