JavaScript / jQuery将数字与相同的优先级组合在一起

时间:2012-10-09 06:43:45

标签: javascript jquery regex arrays json

假设我有这个数组

[1,2,3,4,5,6,7,9]

我想输出的是一个字符串:

"{1 to 7;9}" 

我有这段代码:

var _checkbox = [1,2,3,4,5,6,7,9];
for (i=0; i<_checkbox.length; i++) {
    //if ($($(_checkbox)[i]).is(":checked"))
       ignore_response_from.push(i+1)
}

我唯一的问题是输出字符串“{1到7; 9}”。我该怎么做?

6 个答案:

答案 0 :(得分:2)

这应该可以解决问题:

var _checkbox = [1,2,3,4,5,6,7,9],
    start=null, out= [];
for (i=0; i<_checkbox.length; i++) {
    if(start === null) {
        if(_checkbox.length < i+1 || _checkbox[i+1] !== _checkbox[i]+1){
            out.push(_checkbox[i]);
        } else {
            start=_checkbox[i];
        }
    } else {
        if(_checkbox.length < i+1 || _checkbox[i+1] !== _checkbox[i]+1){
            out.push(start + " to " + _checkbox[i]);
            start=null;            
        }
    }
}
console.log( '{' + out.join(';') + '}');

http://jsfiddle.net/Vandeplas/HzdsG/

更新 的 将它移动到函数中并使用与epoch相同的测试数据进行比较

http://jsfiddle.net/Vandeplas/HzdsG/2/

答案 1 :(得分:2)

在这里,我已经包含了一个基本的测试用例:

var tests = [
    [1,2,3,4,5,6,7,9],
    [1,2,3,4,5,6,7,12,13,14,15,16,20],
    [1,2,3,4,5,6,7,12,13,14,15,16,20,21,22,23],
    [1,2,3,4,5,6,7,120,13,14,15,16,2890,21,22,23],
    [1,2,3,4,8,9,10,11,12,14,16,18,20,21,22,23,30,31,34]
];

var processArray = function(arr, sep) {
    var l = arr.length, i, sl, res = [], succ = [];

    for (i = 0; i < l; i++) {
        var c = (i != 0 && (arr[i - 1] + 1 !== arr[i]));
        if ((i == l - 1) || c) {   
             if (!c) succ.push(arr[i]);

             if ((sl = succ.length) > 0) {
                 res.push(succ[0] + sep + succ[sl - 1]);
                 succ = [];
             } 

             if (arr[i + 1] - 1 === arr[i]) {
                 succ.push(arr[i])
             } else if (c) {
                 res.push(arr[i]);
             }
         } else {
             succ.push(arr[i]);                 
         }
    }

    return res;
}

// setup
for (var i = 0; i < tests.length; i++) {
    console.log('Test ' + i + ' : { ' + processArray(tests[i], ' to ').join('; ') + ' }');
}

这是fiddle

答案 2 :(得分:1)

这是我想到的第一种方法。是的, 丑陋,但似乎有效:

function renderArray(_checkbox) {
    var output = [],
        rangeStart = 0;

    function outputCurrent() {
        if (rangeStart < i - 1)
            output.push(_checkbox[rangeStart] + " to " + _checkbox[i - 1]);
        else
            output.push(_checkbox[i - 1]);
        rangeStart = i;
    }
    for (var i = 1; i < _checkbox.length; i++)
        if (_checkbox[i] != _checkbox[i - 1] + 1)
           outputCurrent();
    outputCurrent();

    return "{" + output.join("; ") + "}";
}

console.log(renderArray([1,3,4,5,7,9,10,11,14]));
// logs "{1; 3 to 5; 7; 9 to 11; 14}"

演示:http://jsfiddle.net/Jq2sQ/2/

答案 3 :(得分:0)

你的意思是:

var _checkbox = [1,2,3,4,5,6,7,9], ignore_response_from= "{";
for (i=0; i<_checkbox.length; i++) {
    //if ($($(_checkbox)[i]).is(":checked"))
       ignore_response_from += (i+1)+",";
}
ignore_response_from += "}";

ignore_response_from将为字符串格式的“{1,2,3,4,5,6,7,8,}”。

答案 4 :(得分:0)

您可以使用Array.filter创建数组,然后将结果转换为字符串:

function combineEqualPrecedence(arr) {
 var combined = arr.filter(
      function(a,i,x){
       var cando = a-(x[i+1]||0) !== prev;
       prev = a-(x[i+1]||0);
       return cando;
      }, prev = 0
     )
    ,str = [];
 for (var i=0;i<combined.length;i+=2){
  str.push(combined[i+1] ? combined[i] + ' to '+ combined[i+1] : combined[i])
 }
 return '{'+str.join('; ')+'}';
}
// usage
combineEqualPrecedence([1,2,3,4,5,6,7,9]); 
              //=> {1 to 7; 9}
combineEqualPrecedence([1,2,3,4,5,6,7,9,10,11,13,14,15,17]); 
              //=> {1 to 7; 9 to 11; 13 to 15; 17}

答案 5 :(得分:-1)

试试这个

"{" + _checkbox[0] + "to" + _checkbox.slice(_checkbox.length -2).join(';') +"}"