gpt4 book ai didi

javascript - 将字符串转换为基元

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

我希望尽可能以安全传递任何值的方式将字符串强制转换为基元。我正在寻找一种更“原生”的方法,而不是试图涵盖所有可能的情况。

value("0") //0
value("1") //1
value("-1") //-1
value("3.14") //3.14
value("0x2") //2
value("1e+99") //1e+99

value("true") //true
value("false") //false
value("null") //null
value("NaN") //NaN
value("undefined") //undefined
value("Infinity") //Infinity
value("-Infinity") //-Infinity

value("") //""
value(" ") //" "
value("foo") //"foo"
value("1 pizza") //"1 pizza"

value([]) //[]
value({}) //{}

value(0) //0
value(1) //1
value(-1) //-1
value(3.14) //3.14
value(0x2) //2
value(1e+99) //1e+99

你明白了

function value(x){
if(typeof x==="string"){
if(x=="") return x;
if(!isNaN(x)) return Number(x);
if(x=="true") return true;
if(x=="false") return false;
if(x=="null") return null;
if(x=="undefined") return undefined;
}
return x;
}

主要问题是因为 isNaN() 对于诸如

之类的东西返回“is a Number”
"" empty strings
" " blank strings
[] arrays
etc

编辑

基于已接受的答案:

function value(x) {
if (typeof x === "string") {
switch (x) {
case "true": return true;
case "false": return false;
case "null": return null;
case "undefined": return void 0;
}
if (!isNaN(x) && !isNaN(parseFloat(x))) return +x;
}
return x;
}

最佳答案

您的代码存在的问题是,仅使用 isNaN 无法正确检测数字字符串。

例如,由于 +""=== 0,则 isNaN("") === false

相反,我建议使用 this list of testcases 的第二个 isNumeric 函数,取自Validate decimal numbers in JavaScript .

function isNumeric(n) {
return !isNaN(n) && !isNaN(parseFloat(n));
}
function value(x){
if(typeof x !== "string") return x;
switch(x) {
case "true": return true;
case "false": return false;
case "null": return null;
case "undefined": return void 0;
}
if(isNumeric(x)) return +x;
return x;
}

关于javascript - 将字符串转换为基元,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33320832/

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