如何計算給定數字的位數?JavaScript
此處的要求很簡單,我們需要編寫一個 JavaScript 函式,獲取一個數字並返回其位數。
例如 −
The number of digits in 4567 is 4 The number of digits in 423467 is 6 The number of digits in 457 is 3
讓我們編寫此函式的程式碼 −
示例
const num = 2353454;
const digits = (num, count = 0) => {
if(num){
return digits(Math.floor(num / 10), ++count);
};
return count;
};
console.log(digits(num));
console.log(digits(123456));
console.log(digits(53453));
console.log(digits(5334534534));輸出
控制檯中的輸出為 −
7 6 5 10
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP