You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript将数组中的负数转换为正数?

如何将JavaScript数组中的负数转换为正数?

原始输入数组:

const numbers = [200, 450, -400, 3000, -650, -130, -70, 1300];

期望输出:

const numbers = [200, 450, 400, 3000, 650, 130, 70, 1300];

方法1:使用Array.map()和Math.abs()

这是最简洁高效的方案,Math.abs()会直接返回数字的绝对值,配合map()遍历数组生成新数组:

const numbers = [200, 450, -400, 3000, -650, -130, -70, 1300];
const positiveNumbers = numbers.map(num => Math.abs(num));
console.log(positiveNumbers); // [200, 450, 400, 3000, 650, 130, 70, 1300]

方法2:手动判断转换

如果需要手动实现逻辑(便于理解原理),可以通过条件判断处理负数:

const numbers = [200, 450, -400, 3000, -650, -130, -70, 1300];
const positiveNumbers = numbers.map(num => num < 0 ? -num : num);
console.log(positiveNumbers); // 输出目标数组

方法3:修改原数组(不推荐)

若必须修改原数组而非生成新数组,可使用forEach()遍历修改:

const numbers = [200, 450, -400, 3000, -650, -130, -70, 1300];
numbers.forEach((num, index) => {
  if (num < 0) {
    numbers[index] = -num;
  }
});
console.log(numbers); // 原数组被修改为目标数组

注意:通常推荐生成新数组,避免修改原数组带来的副作用。

内容的提问来源于stack exchange,提问作者zotta212

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 10:45:44