使用 JavaScript 反轉陣列中整數的符號


問題

我們需要編寫一個接受一個整數陣列(正數和負數)的 JavaScript 函式。

我們的函式應將所有正數轉換為負數,所有負數轉換為正數,並返回結果陣列。

示例

以下為程式碼:

 即時演示

const arr = [5, 67, -4, 3, -45, -23, 67, 0];
const invertSigns = (arr = []) => {
   const res = [];
   for(let i = 0; i < arr.length; i++){
      const el = arr[i];
      if(+el && el !== 0){
         const inverted = el * -1;
         res.push(inverted);
      }else{
         res.push(el);
      };
   };
   return res;
};
console.log(invertSigns(arr));

輸出

[ -5, -67, 4, -3, 45, 23, -67, 0 ]

更新於: 17-4-2021

158 次瀏覽

職業生涯起步

透過完成課程獲得認證

開始
廣告