2017-01-17 100 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; 
} 
相關問題