javascript - 使用javascript将数组中的所有负值更改为正值

标签 javascript

如何使用 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+ 匹配小数点前的数字
  • .?匹配小数 01 次。
  • \d{0,2} 匹配小数点后 2 位数字。

关于javascript - 使用javascript将数组中的所有负值更改为正值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48742891/

相关文章:

javascript - 为什么以及何时使用 angular.copy? (深拷贝)

php - 浏览器关闭时显示弹出窗口

javascript - 如何使用按钮执行 ng-include ?

javascript - 检查并添加数组对象中的属性

javascript - 如何在我的网站上使用单独的 javascript 文件

javascript - 未捕获错误 :expected a string. 您忘记从其定义的文件中导出您的组件,或者您可能混淆了默认/命名导入

javascript - 触发文本框中文本的更改

PHP + JavaScript 倒计时回显 5 秒/1 秒

javascript - 如何在函数上打数据库?

php - 如何在 Facebook 页面选项卡中授权用户?