需要領取:
數字化(12345)-> [5,4,3,2,1]
我寫了一段代碼:
function digitize(n) {
let arr = Array.from(n '');
return arr.reverse();
}
console.log(digitize(12345));
輸出:['5','4','3','2','1']
這非常接近,但這顯示了一個字串陣列。我怎樣才能得到一個數字陣列(不帶引號)呢?
uj5u.com熱心網友回復:
您可以將(的第二個引數Array.from)與Number.
此方法僅適用于等于或小于Number.MAX_SAFE_INTEGER( 9007199254740991) 的正整數。
function digitize(n) {
return Array
.from(n.toString(), Number)
.reverse();
}
console.log(digitize(12345));
uj5u.com熱心網友回復:
您可以考慮使用遞回函式,并且無需轉換為字串即可:
function digitize(n) {
return n < 10 ? [n] : [n % 10, ...digitize(Math.floor(n / 10))];
}
console.log(digitize(12345));
uj5u.com熱心網友回復:
我不會在這里通過字串化走“hacky”、錯誤且可能效率較低的路線:
function digitize(n) {
// remove the below line if you want digitize(0) to be []
if (n === 0) return [0]; // adapt this edge case to your needs;
const digits = [];
while (n >= 1) {
digits.push(n % 10);
n = Math.floor(n / 10);
}
return digits;
}
或使用 ado-while取決于您是否digitize(0)想要[0]沒有if:
function digitize(n) {
const digits = [];
do {
digits.push(n % 10);
n = Math.floor(n / 10);
} while (n >= 1)
return digits;
}
但是,由于精度問題,這對于一些大型浮點數仍然會失敗。
uj5u.com熱心網友回復:
嘗試
// 以下函式將為您提供一個數字陣列,該陣列按作為函式引數給出的數字的數字的降序排列
function digitize(n) {
const str = n.toString();
const myArr = str.split("");
const reversedArr = myArr.map(function (x) {
return parseInt(x, 10);
}).sort((a,b)=>{return b-a});
return reversedArr
}
console.log(digitize(12345))
console.log(digitize(45343))
console.log(digitize(484643))
// [5, 4, 3, 2, 1]
// [5, 4, 4, 3, 3]
// [8, 6, 4, 4, 4, 3]
// 以下函式將為您提供一個數字陣列,這些數字與作為函式引數給出的數字的數字相反
function digitize(n) {
const str = n.toString();
const myArr = str.split("");
const reversedArr = myArr.map(function (x) {
return parseInt(x, 10);
}).reverse();
return reversedArr
}
console.log(digitize(12345));
console.log(digitize(45343));
console.log(digitize(484643));
// [5, 4, 3, 2, 1]
// [3, 4, 3, 5, 4]
// [3, 4, 6, 4, 8, 4]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/466182.html
標籤:javascript
