![](/img/trans.png)
[英]How do you separate a javaScript variable's Whole number and it's decimal to style them separately?
[英]How can I separate whole javaScript numbers and multiply them separately
我想做的是將整數分開,例如1986或364,然后將其添加到數組中,例如[1000,900,80,6]或[300,60,4],無論大小是多少數。
function convert(num) {
var numbers = String(num).split("");
var times = [1000, 100, 10, 1];
var converted = [];
for(var i = 0; i < numbers.length; i++){
converted.push(numbers[i] * times[times.length - numbers.length + i]);
}
return converted;
}
convert(360);
它將適用於任意數量的數字
function convert(num) { var temp = num.toString(); var ans = []; for (var i = 0; i < temp.length; i++) { //get the ith character and multiply with correspondng powers of 10 ans.push(parseInt(temp.charAt(i)) * Math.pow(10, temp.length - i - 1)); } return ans; } convert(39323680);
正如@James Thorpe提到的那樣,您需要定義更適合自己的內容,但這似乎比較簡潔,並且支持任何數字(不僅是4位數字)
function seperateNumber(num) { var seperated = []; while (num > 0) { var mod = num % 10; seperated.push(mod); num = (num - mod) / 10; } return seperated; } console.log(seperateNumber(1986));
您是否要轉換更高的數字?
您可以嘗試這樣的操作(雖然不是很優雅):
function convert(num) { var numbers = String(num).split(""); converted = []; numbers.reverse(); numbers.forEach(function(element, index) { converted.push(element*Math.pow(10,index)); }); return converted.reverse(); } console.log(convert(19813));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.