2017-01-17 66 views
0

我想创建一个程序,它需要一个数字是输入,例如:12345,然后将此数字拆分为2位数字并将其存储在数组中。数组必须如下所示:[0] = 45 [1] = 23 [2] = 1。这意味着数字的分割必须从数字的最后一位开始,而不是第一位。Array删除一个数字的最后两位数

这是我到现在为止:

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但是我需要最后一个数组有两个数字,第一个应该是一个数字,而不是像这样:[0] = 1 [ 1] = 23 [2] = 45

+0

你尝试过什么?你有任何代码告诉我们你已经做了什么吗? – birryree

+0

我们是否假设输入总是整数? – virtuexru

+0

是的,我有这段代码(已在上面添加) – Kenneth

回答

0

非常粗糙,但这应该工作该字符串始终号码:

input = "12345" 

def chop_it_up(input) 
    o = [] 

    while input.length > 0 
    if input.length <= 2 
     o << input 
    else 
     o << input[-2..input.length] 
    end 
    input = input[0..-3] 
    chop_it_up(input) 
    end 

    return o 
end 
+0

我忘了说我需要它在JS – Kenneth

+0

将我在Ruby中编写的代码转换成JS,并不难。 – virtuexru

+0

它可能不是,但我是很新的编码,只有15,我不知道Ruby的线索,目前正在尝试学习JS。我会非常感激,如果你可以帮助我的那个 – Kenneth

0

我大概折腾这样的:

int[] fun(int x){ 
    int xtmp = x; 
    int i = 0; 
    int len = String.valueOf(x).length(); 
    // this is a function for java, but you can probably find 
    //an equivalent in whatever language you use 
    int tab[(len+1)/2]; 
    while(xtmp > 1){ 
     tab[i] = xtmp%100; 
     xtmp = int(xtmp/100); // here you take the integer part of your xtmp 
     ++i; 
    } 
    return tab; 
} 
相关问题