gpt4 book ai didi

javascript - 将字符串解析为 bool、float、number、date 或 string

转载 作者:行者123 更新时间:2023-12-03 03:00:16 25 4
gpt4 key购买 nike

假设我可以控制输入,我可以创建一个函数,根据“最佳猜测”将字符串转换为正确的类型。

'2017-12-24' -> string '2017-12-24' (implement with a simple regex)
'2017' -> number 2017 (implement with parseInt - ok to ignore any letters that follows)
'201.7' -> float 201.7 (implement with parseFloat - ok to ignore any letters that follows)
'True' -> bool true (implement with [].indexOf - TRUE, False, false, true also)
'foo' -> string 'foo' (implement withreqex - anything starting with a letter)
'' -> null

是否有任何库已经做到了这一点?

最佳答案

upcast

upcast 是一个 JS 类型检查/转换库。一些例子:

upcast.type([]); // 'array'
upcast.is(123, 'string'); // false
upcast.to('foo', 'array'); // ['f', 'o', 'o']

这个库可能无人维护,但您会想到编写自己的库。

关于javascript - 将字符串解析为 bool、float、number、date 或 string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47434462/

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