【发布时间】:2017-06-01 19:20:22
【问题描述】:
我想创建一个程序,输入一个数字,例如:12345,然后将此数字拆分为2位数字并将其存储在一个数组中。数组必须如下所示: [0]=45 [1]=23 [2]=1 。这意味着数字的拆分必须从数字的最后一位而不是第一位开始。
这是我到现在为止的:
var splitCount = []; // This is the array in which we store our split numbers
//Getting api results via jQuery's GET request
$.get("https://www.googleapis.com/youtube/v3/channels?part=statistics&id=UCJwchuXd_UWNxW-Z1Cg-liw&key=AIzaSyDUzfsMaYjn7dnGXy9ZEtQB_CuHyii4poc", function(result) {
//result is our api answer and contains the recieved data
//now we put the subscriber count into another variable (count); this is just for clarity
count = result.items[0].statistics.subscriberCount;
//While the subscriber count still has characters
while (count.length) {
splitCount.push(count.substr(0, 2)); //Push first two characters into the splitCount array from line 1
count = count.substr(2); //Remove first two characters from the count string
}
console.log(splitCount) //Output our splitCount array
});
但问题在于,如果有 5 个数字,例如:12345,最后一个数字将单独存在于一个数组中,如下所示:[0]=12 [1]=34 [2]=5 但我需要最后一个数组有 2 个数字,第一个应该是一个数字,而不是像这样:[0]=1 [1]=23 [2]=45
【问题讨论】:
-
你试过什么?您有任何代码可以向我们展示您已经完成的工作吗?
-
我们是否假设输入总是整数?
-
是的,我有这个代码(在上面添加)
标签: javascript arrays split slice digit