使用 split() 在 JavaScript 中對數字的每一位進行平方
我們需要編寫一個 JavaScript 函式,其第一個也是唯一一個引數是數字。然後,該函式應將數字的每一位平方,將它們追加,並生成新的數字。
例如 −
如果輸入的數字為 −
const num = 12349;
那麼輸出應為 −
const output = 1491681;
因為 '1' + '4' + '9' + '16' + '81' = 1491681
示例
其程式碼將為 −
const num = 12349;
const squareEvery = (num = 1) => {
let res = ''
const numStr = String(num);
const numArr = numStr.split('');
numArr.forEach(digit => {
const square = (+digit) * (+digit);
res += square;
});
return +res;
};
console.log(squareEvery(num));輸出
控制檯中的輸出將為 −
1491681
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP