【发布时间】:2017-06-01 22:57:58
【问题描述】:
(必须阅读以了解我需要什么) 我想创建一个程序,输入一个数字,例如: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
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
但问题在于,如果有 5 个数字,例如:12345,最后一个数字将单独存在于一个数组中,如下所示:[0]=12 [1]=34 [2]=5 但我需要最后一个数组有 2 个数字,第一个应该是一个数字,而不是像这样:[0]=1 [1]=23 [2]=45
【问题讨论】:
-
尝试从字符串末尾开始
-
但它是一个整数?你能帮帮我吗?
-
通过将它连接到一个 "" 使其成为一个字符串,然后使用 paresInt() 方法返回一个 int
-
您在问题的第一部分声明
12345的输出应该像[0]=45 [1]=23 [2]=1,但在最后一部分像[0]=1 [1]=23 [2]=45。是哪个?
标签: javascript arrays split int