将整数分割成2位数并放入数组Javascript

时间:2017-01-17 18:39:50

标签: javascript arrays split int

(必读以明确我需要的内容) 我想创建一个程序,输入一个数字,如: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>
&#13;
&#13;
&#13;

但问题是,如果有5个数字,例如:12345,最后一个数字本身就是一个数组:[0] = 12 [1] = 34 [2] = 5但我需要最后一个数组有2位数,第一个应该是一位数,而不是像这样:[0] = 1 [1] = 23 [2] = 45

6 个答案:

答案 0 :(得分:3)

使用不同的正则表达式对奇数和偶数字符串长度分割字符串,if ($('.flex-control-thumbs').hasClass('active')) { $(this).find('li').attr('data-thumb', 'assets/img/active-nav-slide.png'); } 使用Array#mapNumber数组:

&#13;
&#13;
Array#reverse
&#13;
&#13;
&#13;

答案 1 :(得分:1)

这是一个完成任务的片段。该函数将值存储在数组myArray中,然后将数组输出到<p>元素。该数字输入到输入框中。随后可以随意更改。

function myFunction() {
  // Input field
  var input = document.getElementById('num');1
  // Length of the array storing the numbers
  var myArraySize = Math.floor(input.value.length / 2) + (input.value.length % 2);
  // The array storing the numbers
  var myArray = [];
  
  for (var i = 0; i < myArraySize; i++) {
    myArray[i] = input.value.slice(2*i,2*i+2);
  }
  // Output the array
  document.getElementById('demo').innerHTML = myArray;
}
<input id="num" type="text" onkeyup="myFunction()" />
<p id="demo">Result</p>

答案 2 :(得分:1)

您可以使用正则表达式拆分字符串并反转数组。

这个答案深受这个answer的启发。

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<div class="container-fluid" ng-app="example">
  <div class="container" ng-controller="exampleController">
    <input class="row" ng-model="number1">
    <input class="row" ng-model="number2">
    <input class="row" ng-model="sum">

    <h1>Multiply sum by 2: {{sum * 2}}</h1>
  </div>
</div>
&#13;
var regex = /(?=(?:..)*$)/;

console.log('12345'.split(regex).reverse());
console.log('012345'.split(regex).reverse());
&#13;
&#13;
&#13;

答案 3 :(得分:1)

无需正则表达式或昂贵的计算。您可以简单地执行以下操作;

&#13;
&#13;
var n = 250847534,
steps = ~~Math.log10(n)/2,
  res = [];
for(var i = 0; i <= steps; i++) {
  res.push(Math.round(((n /= 100)%1)*100));
  n = Math.trunc(n);
}
console.log(res);
&#13;
&#13;
&#13;

答案 4 :(得分:0)

稍微修改你的代码

&#13;
&#13;
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(-2)); //Push last two characters into the splitCount array from line 1
        if(count.length > 1) {
           count =  count.substr(0, count.length - 2); //Remove first last two characters from the count string
        } else {
           break;
        }
    }       
    console.log(splitCount) //Output our splitCount array
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 5 :(得分:0)

有几种方法可以解决您的问题,从使用正则表达式(如Ori DoriNina Scholz)到Redu's answer的优秀单行程序直接处理数字,避免使用字符串。

遵循代码示例和注释的逻辑,这里有一个替代方法,将数字转换为字符串,向后循环以一次提取两个数字,将这些数字转换回数字(使用一元加运算符) ,并将此数字输出到结果数组:

function extract(num) {
  var s = '0' + num, //convert num to string
    res = [],
      i;
  for(i = s.length; i > 1; i -= 2) {
    //loop from back, extract 2 digits at a time, 
    //output as number,
    res.push(+s.slice(i - 2, i));
  }
  return res;
}

//check that 12345 outputs [45, 23, 1]
console.log(extract(12345));

//check that 123456 outputs [56, 34, 12]
console.log(extract(123456));