gpt4 book ai didi

javascript - 判断字符串是日期还是数字

转载 作者:行者123 更新时间:2023-11-27 23:04:21 34 4
gpt4 key购买 nike

我正在尝试确定字符串是数字还是日期。

这是我的代码:

this._getFieldFormat = (value) => {

// check if is date
let d = new Date(value);

if (!isNaN( d.getTime() ) ) {
return 'date';
}

// check if is boolean
// isNaN(false) = false, false is a number (0), true is a number (1)
if(typeof value === 'boolean'){
return 'boolean';
}

// check if a string is a number
if(!isNaN(value)){
return 'number';
}

return typeof value;
};

它适用于如下日期:2016-04-19T23:09:10.208092Z。问题在于 1 看起来是有效日期 (Wed Dec 31 1969 16:00:00 GMT-0800 (PST)) 和 isNaN(new Date ()) 是 return false (日期是一个数字)。

知道如何摆脱这个循环吗?

最佳答案

所以发生的事情称为强制。由于 javascript 是动态类型,当您给它两种不同的类型时,js 引擎会尝试将其中一种类型强制转换为合理的类型或它认为您的意思。

例如:

isNan("37"); is false because "37" is converted to the number 37

isNaN(new Date()) is return false (a date is a number)

它将日期转换为数字,因此这是正确的。

However, invalid values in date strings not recognized as ISO format as defined by ECMA-262 may or may not result in NaN, depending on the browser and values provided

所以

new Date('23/25/2014'); // NON-ISO string with invalid date values

因此,这将在所有符合 ES5 及更高版本的浏览器中返回 NaN。

还要进行更严格的检查,您可以使用:

Number.isNan(new Date()); // This should return true

因此,回顾一下,请确保日期符合 ISO 标准,否则它将是 NaN 并使用更严格的检查。希望这会有所帮助。

关于javascript - 判断字符串是日期还是数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36731678/

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