在数组内的偶数之间插入连字符

时间:2015-02-28 20:56:15

标签: javascript arrays

我正在尝试在数组中的偶数之间插入连字符“ - ”,如果我有43268356925485942568则显示432-6-83569254-8594-256-8。这些数字是随机生成的。我尝试了几件事,但没有运气。

<body>
    <div id="arrayDisp">
    </div>
    <div id="numbers"> 

    </div>
    <script>
        var numbers = new Array(20);
        var numbers2 = new Array(20)

        for (var i = 0; i< numbers.length; i++)
        {
            numbers[i] = parseInt(Math.random() * 10);
        }

        document.getElementById("arrayDisp").innerHTML = numbers.join(" ");

        for(var i in numbers)  
        {  
            if(i%2 == 0)
            {  
                numbers2.push('‐',i);
            }  
            else  
            {  
                numbers2.push(i);  
            }  
        }           
        document.getElementById("numbers").innerHTML = numbers2.join("");

    </script>
</body>

5 个答案:

答案 0 :(得分:4)

只需查看当前和下一个号码,看看它们是否均匀?

&#13;
&#13;
function addHyphen(str) {
    var arr = str.split('');
        
    return arr.map(function(n, i) {
        return (n % 2 === 0) && (arr[i+1] % 2 === 0) ? n+'-' : n;
    }).join('');
}

// provided number
var s       = '43268356925485942568';
var result1 = addHyphen(s);

// create random number
var rand = (new Array(20)).join('s').split('s').map(function(x) { 
    return parseInt(Math.random() * 10, 10);
}).join('');

var result2 = addHyphen(rand);

document.body.innerHTML = result1 + '<br />' + result2;
&#13;
&#13;
&#13;

答案 1 :(得分:2)

您可以使用正则表达式查找偶数数字后跟另一个数字并在其中插入短划线:

&#13;
&#13;
var numbers = '';
for (var i = 0; i < 20; i++) {
  numbers += Math.floor(Math.random() * 10);
}

numbers = numbers.replace(/([02468])(?=[02468])/g, '$1-');

// show in Stackoverflow snippet
document.write(numbers);
&#13;
&#13;
&#13;

说明:

()           captures a match
([02468])    matches an even digit and captures it
(?=)         is a positive look-ahead
(?=[02468])  matches when the next digit is even

替换字符串使用$1插入捕获的数字,然后插入破折号。

答案 2 :(得分:1)

我不明白为什么每个人都会提出过复杂(有时候是非功能性的)代码。 这是一项简单的任务!没有回调,需要正则表达式,甚至不能让代码易于理解!

使用Array.splice并使用原始数组

/** Requires array of numbers, changes THAT array, returns null 
  * @param numbers array of numbers
**/
function addHyphenWhenEven(numbers) {
  for(var i=1, l=numbers.length;i<l; i++) {
    if((numbers[i]%2 + numbers[i-1]%2) == 0) {
      //Splice inserts 3rd parameter before i-th position
      numbers.splice(i, 0, "-"); 
      //Must shift the positions as the array dimensions have changed
      i--;l++;
    }      
  }
}

使用新数组

/** Requires array of numbers, returns new array with hyphens
  * @param numbers array of numbers
  * @return array with numbers and hyphens
**/
function addHyphenWhenEven2(numbers) {
  if(numbers.length==0)
    return [];
  var result = [numbers[0]];
  for(var i=1, l=numbers.length;i<l; i++) {
    if((numbers[i]%2 + numbers[i-1]%2) == 0) {
      result.push("-");
    }
    result.push(numbers[i]);  
  }
  return result;
}

/** Requires array of numbers, changes THAT array, returns null 
      * @param numbers array of numbers
    **/
    function addHyphenWhenEven(numbers) {
      for(var i=1, l=numbers.length;i<l; i++) {
        if((numbers[i]%2 + numbers[i-1]%2) == 0) {
          //Splice inserts 3rd parameter before i-th position
          numbers.splice(i, 0, "-"); 
          //Must shift the positions as the array dimensions have changed
          i--;l++;
        }      
      }
    }

    /** Requires array of numbers, returns new array with hyphens
      * @param numbers array of numbers
      * @return array with numbers and hyphens
    **/
    function addHyphenWhenEven2(numbers) {
      if(numbers.length==0)
        return [];
      var result = [numbers[0]];
      for(var i=1, l=numbers.length;i<l; i++) {
        if((numbers[i]%2 + numbers[i-1]%2) == 0) {
          result.push("-");
        }
        result.push(numbers[i]);  
      }
      return result;
    }
var random = [];
while(random.length<20)
{
  random.push(Math.floor(Math.random()*10));  
}

$("#res2")[0].innerHTML = addHyphenWhenEven2(random).join("");

addHyphenWhenEven(random);
$("#res1")[0].innerHTML = random.join("");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<h2>Using <tt>Array.splice</tt></h2>
<div id="res1"></div>
<h2>Using second array that is returned:</h2>
<div id="res2"></div>

答案 3 :(得分:0)

var numbers = [];
var hiphenated = [];
for (var i = 0; i < 20; i++) {
    numbers.push(parseInt(Math.random() * 10));
}

numbers.forEach(function(n) {
   if (n % 2 == 0) {
    hiphenated.push(n + '-');
   } else {
    hiphenated.push(n);
   }                      
});

答案 4 :(得分:0)

var s = "43268356925485942568";

s = s.split('').reduce(function(a, b) {
  return  a + ((!a || (a.slice(-1) & 1) || (b & 1))? '' : '-') + b;
}, '');