gpt4 book ai didi

javascript - 为什么要使用 toString() 来对可以使用 typeof 检查的参数进行类型检查?

转载 作者:可可西里 更新时间:2023-11-01 02:56:47 25 4
gpt4 key购买 nike

我理解为什么您需要使用 Object.prototype.toString()String() 来对数组进行类型检查,但不是 typeof足以对函数和字符串进行类型检查吗?例如 MDN 上的 polyfill Array.isArray用途:

Object.prototype.toString.call(arg) == '[object Array]';

在数组的情况下很明显,因为您不能使用 typeof 来检查数组。 Valentine使用 instanceof为此:

ar instanceof Array

但是对于字符串/函数/ bool 值/数字,为什么不使用typeof呢?

jQueryUnderscore两者都使用类似这样的方法来检查功能:

Object.prototype.toString.call(obj) == '[object Function]';

这不就相当于这样做了吗?

typeof obj === 'function'

甚至这个?

obj instanceof Function

最佳答案

好的,我想我明白了为什么您会看到 toString 用法。考虑一下:

var toString = Object.prototype.toString;
var strLit = 'example';
var strStr = String('example')​;
var strObj = new String('example');

console.log(typeof strLit); // string
console.log(typeof strStr); // string
console.log(typeof strObj); // object

console.log(strLit instanceof String); // false
console.log(strStr instanceof String); // false
console.log(strObj instanceof String); // true

console.log(toString.call(strLit)); // [object String]
console.log(toString.call(strStr)); // [object String]
console.log(toString.call(strObj)); // [object String]

关于javascript - 为什么要使用 toString() 来对可以使用 typeof 检查的参数进行类型检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9512661/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com