【问题标题】:Split Integer into 2 digits and put into array Javascript将整数拆分为 2 位数字并放入数组 Javascript
【发布时间】: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


【解决方案1】:

对奇数和偶数字符串长度使用不同的正则表达式拆分字符串,Array#map 使用NumberArray#reverse 数组:

function splitToNumbers(str) {
  return str.match(str.length  % 2 ? /^\d|\d{2}/g : /\d{2}/g).map(Number).reverse()
}
    
console.log(splitToNumbers('1234567'));

console.log(splitToNumbers('123456'));

【讨论】:

    【解决方案2】:

    这是一个完成任务的sn-p。该函数将值存储在数组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>

    【讨论】:

      【解决方案3】:

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

      这个答案深受answer 的启发。

      var regex = /(?=(?:..)*$)/;
      
      console.log('12345'.split(regex).reverse());
      console.log('012345'.split(regex).reverse());
      .as-console-wrapper { max-height: 100% !important; top: 0; }

      【讨论】:

        【解决方案4】:

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

        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);

        【讨论】:

          【解决方案5】:

          稍微修改你的代码

          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
          });
          &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

          【讨论】:

            【解决方案6】:

            有几种方法可以解决您的问题,从使用正则表达式(如 Ori DoriNina Scholz)的漂亮单行代码到直接处理数字而不使用字符串的 Redu's answer

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

            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));

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2010-12-26
              • 2016-11-28
              • 1970-01-01
              • 1970-01-01
              • 2015-10-16
              相关资源
              最近更新 更多