[英]Convert each element of array into separate array in JavaScript (ES6)
[英]Javascript (ES6) convert number into string array of powers of 2
是否有任何智能內聯/單行(ES6)將數字(整數)轉換為字符串數組,該數組獲得數字的二進制冪(pow(2,x))的位位置? IE
13 => ["1","3","4"] // (pow(2,1) + pow(2,3) + pow(2,4)) = 13
如果你真的想要一個 2 的冪數組,這將導致數字,那么對於 13,你會想要:
2 ** 0 = 1
2 ** 2 = 4
2 ** 3 = 8
1 + 4 + 8 = 13
也就是說 - [0, 2, 3]
是導致 13 的冪。
.toString(2)
將一個數字轉換為其二進制等價物,因此您可以將該字符串的元素設為 1:
const num = 13; const arr = []; [...num.toString(2)].reverse().forEach((bit, i) => { if (bit === '1') { arr.push(i); } }); console.log(arr);
像所有 JS 代碼一樣,可以將其壓縮為一行,但這很愚蠢 - 最好編寫干凈易讀的代碼而不考慮行長:
const num = 13; const arr = []; [...num.toString(2)].reverse().forEach((bit, i) => { if (bit === '1') { arr.push(i); } }); console.log(arr);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.