首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从"1,2,5-9“这样的字符串中获取所有数字

从"1,2,5-9“这样的字符串中获取所有数字
EN

Code Review用户
提问于 2013-05-13 20:25:16
回答 1查看 5K关注 0票数 7

我需要得到像"1,2,5-9“这样的字符串中的数字,函数应该返回一个包含这些值的列表。

1,2,5,6,7,8,9

我就是这么做的。这是最好的方法,还是有更简单/更好的方法?

代码语言:javascript
复制
function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function getNumbers(stringNumbers) {
  var nums = [];
  var list1 = stringNumbers.split(",");
  var length = list1.length;
  for(var i = 0; i < length; i++) {
    var number = list1[i];
    if(number.indexOf("-") != -1) {
      range = number.split("-");
      if(isNumber(range[0]) && isNumber(range[1])) {
        var min = parseInt(range[0]);
        var max = parseInt(range[1]);

        //edit to accept range like 9-5

        if(min > max){
          var min_ref = min;
          min = max;
          max = min_ref;
        }


        while(min <= max) {
          nums.push(min);
          min++
        };
      }
    } else {
      if(isNumber(number)) {
        nums.push(parseInt(number));
      }
    }
  }

  //edit to sort list at the end
  return nums.sort(function(a,b){return a - b});
};
EN

回答 1

Code Review用户

回答已采纳

发布于 2013-05-14 08:09:20

嗯,这是我的版本,那是跨不同浏览器进行基准测试。可能需要进行一些改进(目前正在为isNumber找到快捷方式),但其工作方式如下:

代码语言:javascript
复制
function getNumbers(stringNumbers) {

    //personal preference, but I got this handy tip from the internet that

    //if you had assignments, better if they are individually var'ed
    var nums = [];
    var entries = stringNumbers.split(',');
    var length = entries.length;

    //for variabes that don't, comma separated
    var i, entry, low, high, range;

    for (i = 0; i < length; i++) {
        entry = entries[i];

        //shortcut for testing a -1
        if (!~entry.indexOf('-')) {
            //absence of dash, must be a number
            //force to a number using +
            nums.push(+entry);
        } else {
            //presence of dash, must be range
            range = entry.split('-');

            //force to numbers
            low = +range[0];
            high = +range[1];

            //XOR swap, no need for an additional variable. still 3 steps though
            //http://en.wikipedia.org/wiki/XOR_swap_algorithm
            if(high < low){
              low = low ^ high;
              high = low ^ high;
              low = low ^ high;
            }

            //push for every number starting from low
            while (low <= high) {
                nums.push(low++);
            }
        }
    }

    //edit to sort list at the end
    return nums.sort(function (a, b) {
        return a - b;
    });
}

这里是另一个版本,它是V2(稍慢),因为我添加了附加的数字检查,上面的检查没有,但是更符合问题的规范。

代码语言:javascript
复制
var getNumbers = (function () {

    //we create a closure so as not to expose some of our utility functions

    function isNumber(n) {
        //we check isFinite first since it will weed out most of the non-numbers
        //like mixed numbers and strings, which parseFloat happily accepts
        return isFinite(n) && !isNaN(parseFloat(n));
    }

    //let's get this one out as well
    //the simple sort() wouldn't work so instead we provide a sorter
    function sorterFunction(a, b) {
        return a - b;
    }

    //getNumbers should be this function
    return function (stringNumbers) {

        //variable declaration format is personal preference
        //but I prefer having declarations with assignments have individual vars
        //while those that have no assignments as comma separated
        var i, range, low, high, entry;

        //an added bonus, " and ' are the same in JS, but order still applies
        //I prefer to use ' since it's cleaner
        var entries = stringNumbers.split(','); 
        var length = entries.length;
        var nums = [];

        for (i = 0; i < length; ++i) {
            entry = entries[i];

            if (isNumber(entry)) {
                //we check if the entry itself is a number. If it is, then we push it directly.
                //an additinal advantage is that negative numbers are valid
                nums.push(+entry);
            } else {

                //if not a number, probably it had the - and not being a negative number
                //only here do we split after we determined that the entry isn't a number
                range = entry.split('-');

                //check if what we split are both numbers, else skip
                if (!isNumber(range[0]) || !isNumber(range[1])) continue;

                //force both to be numbers
                low = +range[0];
                high = +range[1];

                //since we are dealing with numbers, we could do an XOR swap
                //which is a swap that doesn't need a third variable
                //http://en.wikipedia.org/wiki/XOR_swap_algorithm
                if (high < low) {
                    low = low ^ high;
                    high = low ^ high;
                    low = low ^ high;
                }

                //from low, we push up to high
                while (low <= high) {
                    nums.push(low++);
                }
            }
        }
        return nums.sort(sorterFunction);
    }
}());
票数 7
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/26125

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档