【问题标题】:JavaScript/jQuery combine numbers with the same precedenceJavaScript/jQuery 组合具有相同优先级的数字
【发布时间】:2012-09-29 10:37:02
【问题描述】:

假设我有这个数组

[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 to 7;9}”。我该怎么做?

【问题讨论】:

  • 渲染输出?你的意思是console.log? :D
  • [1,2,9] 怎么样?输出应该是 {1 to 2, 9}?
  • alert(your_output_variable) ?
  • 已编辑最后一条语句,请重新检查。 niksvp 是的,兄弟。 Zeta:不,不是这样...... @karaxuna:请重新检查对不起我的不好
  • 指定你想如何输出一个字符串?输出到哪里?

标签: javascript jquery regex arrays json


【解决方案1】:

你是这个意思吗:

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,}”。

【讨论】:

    【解决方案2】:

    您可以使用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}
    

    【讨论】:

      【解决方案3】:

      这是我想到的第一个方法。是的,它丑陋的,但它似乎工作:

      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/

      【讨论】:

        【解决方案4】:

        试试这个

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

        【讨论】:

          【解决方案5】:

          这应该可以解决问题:

          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/

          【讨论】:

            【解决方案6】:

            给你,我也包含了一个基本的测试用例:

            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

            【讨论】:

            • 您的文本大小写失败.. Test 3 : 1 to 7; 120; 13 to 16; 2890; 21 to 22; 23; 应该是:Test 3 : {1 to 7;120;13 to 16;2890;21 to 23} 同上测试 2
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多