如何使用 javascript 将数组
中的所有负值更改为正值,例如:
const arry = [-2.5699, -1.4589, -3.2447, -6.9789 ,-9.213568];
我的结果应该是[2.56, 1.45, 3.24, 6.97, 9.21]
在 JavaScript 中怎么可能?
我尝试使用 Math.abs
但得到 NaN
最佳答案
I tried with Math.abs but I getting NAN
使用 map
var arry = [-2.5699, -1.4589, -3.2447, -6.9789 ,-9.213568];
arry = arry.map( s => Math.abs(s));
演示
var arry = [-2.5699, -1.4589, -3.2447, -6.9789, -9.213568];
arry = arry.map(s => Math.abs(s));
console.log(arry);
编辑
简而言之(正如@pwolaq建议的那样)
arry = arry.map(Math.abs)
编辑2
错过了四舍五入部分
var fnRound = (s) => +String(s).match(/\d+\.?\d{0,2}/)[0];
var arry = [-2.5699, -1.4589, -3.2447, -6.9789, -9.213568];
arry = arry.map(Math.abs).map( fnRound );
演示
var fnRound = (s) => +String(s).match(/\d+\.?\d{0,2}/)[0];
var arry = [-2.5699, -1.4589, -3.2447, -6.9789, -9.213568];
arry = arry.map(Math.abs).map( fnRound );
console.log(arry);
正则表达式解释 /\d+\.?\d{0,2}/
\d+
匹配小数点前的数字- .?匹配小数
0
或1
次。 \d{0,2}
匹配小数点后 2 位数字。
关于javascript - 使用javascript将数组中的所有负值更改为正值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48742891/