gpt4 book ai didi

javascript - Object.prototype.toString.call 和 typeof 之间有什么不同

转载 作者:行者123 更新时间:2023-11-30 12:19:49 24 4
gpt4 key购买 nike

我是 javascript 的新手,我对以下方法的区别感到困惑。

function foo(){};
var bar = new Object();

Object.prototype.toString.call(foo).slice(8, -1); // output "Function"
typeof foo; // output "function"

Object.prototype.toString.call(bar).slice(8, -1); // output "Object"
typeof bar; // output "object"

最佳答案

toString“hack”最常见的应用是找出您正在处理的对象类型:

typeof(new Array())  === "object";
typeof(new Date()) === "object";
typeof(new RegExp()) === "object";

Object.prototype.toString.call(new Array()).slice(8, -1) === "Array";
Object.prototype.toString.call(new Date()).slice(8, -1) === "Date";
Object.prototype.toString.call(new RegExp()).slice(8, -1) === "RegExp";

例如,jQuery 1.11 使用它来 check whether a given object is an array . jQuery 2 及更高版本 uses the native Array.isArray现代浏览器支持。

此外,在很多情况下两者会返回不同的结果,最常见的是在基本类型周围使用对象包装器时:

typeof(new Number(5)) === "object";
Object.prototype.toString.call(new Number(5)).slice(8, -1) === "Number";

typeof(new String("hi")) === "object";
Object.prototype.toString.call(new String("hi")).slice(8, -1) === "String";

关于javascript - Object.prototype.toString.call 和 typeof 之间有什么不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31459821/

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