我有一个解决方案,但看起来很困惑,希望有更好的方法:
编写一个返回数字第 n 位的函数
/*
Write a function that returns the nth digit of a number
digitN(498, 1) // 8
digitN(498, 10) // 9
digitN(498, 100) // 4
*/
function digitN(number, base){
if(base === 1){
return number % 10;
}
if(base === 10){
return Math.floor((number % 100) / 10);
}
if(base === 100){
return Math.floor((number % 1000) / 100);
}
}
console.log(digitN(498, 100))
最佳答案
诀窍是用更少的操作和函数调用来做到这一点。
function digitN(N, base) {
return Math.floor(N / base % 10);
}
或者如果你是一只很酷的猫:
const digitN(N, base) => Math.floor(N / base % 10);
关于javascript - 返回数字中第 n 位数字的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59754137/