更新时间:2022-11-14 16:47:54
一个选项是使用 Number
构造函数,该构造函数返回数字或 NaN
:
One option is using the Number
constructor which returns a number or NaN
:
var res = q.split(',').map(el => {
let n = Number(el);
return n === 0 ? n : n || el;
});
// > "The, 1, 2, Fox, Jumped, 3.33, Over, -0"
// < ["The", 1, 2, " Fox", " Jumped", 3.33, " Over", -0]
如果上述情况令人困惑,则可以用Bergi建议的以下条件替换它:
edit: If the above condition is confusing you can replace it with the following condition which was suggested by Bergi:
return isNaN(n) ? el : n;
如果要修剪字符串元素,还可以使用 String.prototype.trim
方法:
In case that you want to trim the string elements you can also use the String.prototype.trim
method:
return isNaN(n) ? el.trim() : n;