如何使用 JavaScript 分割陣列中每個值的最後 n 位數?


我們有一個這樣的文字陣列 −

const arr = ["", 20191219, 20191220, 20191221, 20191222, 20191223, 20191224, 20191225];

我們需要編寫一個 JavaScript 函式,該函式接受此陣列和一個數字 n,如果相應的元素包含大於或等於 n 個字元,則新元素應僅包含最後 n 個字元,否則元素應保持原樣。

讓我們為這個函式編寫程式碼 −

範例

const arr = ["", 20191219, 20191220, 20191221, 20191222, 20191223,
20191224, 20191225];
const splitElement = (arr, num) => {
   return arr.map(el => {
      if(String(el).length <= num){
         return el;
      };
      const part = String(el).substr(String(el).length - num, num);
      return +part || part;
   });
};
console.log(splitElement(arr, 2));
console.log(splitElement(arr, 1));
console.log(splitElement(arr, 4));

輸出

控制檯中的輸出為 −

[
   '', 19, 20, 21,
   22, 23, 24, 25
]
[
   '', 9, '0', 1,
   2, 3, 4, 5
]
[
   '', 1219, 1220,
   1221, 1222, 1223,
   1224, 1225
]

更新於: 31-Aug-2020

266 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.