按照 JavaScript 中的出生日期查詢生命靈數
生命靈數
個人的生命靈數是透過將此人出生日期中的每個數字相加計算得出,直到縮減為一個單獨的個位數。
問題
我們需要編寫一個 JavaScript 函式,該函式採用“yyyy-mm-dd”格式的日期,並返回該出生日期的生命靈數。
例如,
如果此日期為:1999-06-10
year : 1 + 9 + 9 + 9 = 28 → 2 + 8 = 10 → 1 + 0 = 1 month : 0 + 6 = 6 day : 1 + 0 = 1 result: 1 + 6 + 1 = 8
示例
以下是程式碼 −
const date = '1999-06-10';
const findLifePath = (date = '') => {
const sum = (arr = []) => {
if(arr.length === 1){
return +arr[0]
};
let total = arr.reduce((acc, val) => acc + val);
if (total < 10){
return total
};
return sum(String(total).split("").map(Number));
};
let [year, month, day] = date.split("-")
year = sum(String(year).split("").map(Number));
month = sum(String(month).split("").map(Number));
day = sum(String(day).split("").map(Number));
return sum([year,month,day]);
};
console.log(findLifePath(date));輸出
以下是控制檯輸出 −
8
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP