gpt4 book ai didi

javascript - Object.prototype.toString.call(currentFruit) === "[object Date]"

转载 作者:太空宇宙 更新时间:2023-11-04 14:18:32 25 4
gpt4 key购买 nike

我是 js 新手。我有一个我不理解的 if 条件。你能告诉我这个 if 条件的作用吗?

Object.prototype.toString.call(currentFruit) === "[object Date]"

你能解释一下吗?在下面提供我的代码:

setcurrentFruit: function (fruitName, currentFruit) {
WorklistStorage.set(fruitName, currentFruit, false);
},
getcurrentFruit: function (fruitName) {
var currentFruit = unescapeJSON(WorklistStorage.get(fruitName, false));
if (currentFruit == "undefined" || typeof currentFruit == "undefined" || Object.prototype.toString.call(currentFruit) === "[object Date]") {
var date = new Date();
currentFruit = date.toString();
wholeQueue.setcurrentFruit(fruitName, currentFruit);
//console.log("poppppp");
}
currentFruit = new Date(currentFruit);
return currentFruit;
},

最佳答案

让我们分解一下;

因此 Object.prototype.toString.call(currentFruit) 正在调用 toString 上所有对象 的 native currentFruit。如果在 currentFruit.toString() 上定义或继承了另一个 toString,则这可能与 currentFruit 不同。

Object.prototype.toString 返回 [object X] 形式的 String,其中 Xthis类型,因此将 [object Date]=== 进行比较是在询问 "Is currentFruit a 约会?”

为什么做这个检查比 typeof 更有用?因为 typeof 通常只会返回 "object" ,这通常没有帮助。

instanceof 呢?这将是 true,如果您正在检查的东西也继承自您正在测试的东西,例如,x instanceof Object 通常是 true,这也不总是有帮助。

您可能认为类似的替代方法是测试对象构造函数x.constructor === Date 。这有一组不同的问题,例如如果 throwundefinednullx ing 错误,因此需要更多检查等。但如果您正在工作,它会更有帮助对于非本地构造函数,toString 将简单地给出 [object Object]


综上所述,您需要考虑在您所使用的环境下此测试是否永远正确。目前没有标准的 JSON 表示日期

关于javascript - Object.prototype.toString.call(currentFruit) === "[object Date]",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18885015/

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