试图检测数组中的三个数字是否连续出现

时间:2017-11-15 00:03:06

标签: javascript

我正在创建一个以数值作为参数的函数。从那里,目标是检测连续出现三个数字,例如3415633356将传递为真,而3562455则不传递。

我在我的函数中做错了一些应该传递的场景,因为它不是真的。检测连续出现三个数字的最终目标是否可以以任何方式完成。

顺便说一句,我是编程新手,刚刚开始,所以当我练习这些东西时,我正在努力增加知识。如果您可以分析为什么您的建议工作和我做错了而不仅仅是提供唯一的答案,那将非常感激。非常感谢!

var testNumbers = function(num1){
  var stringOne = num1.toString();
  var num1array = stringOne.split("");
  var tripleNum = [];
  num1array.reduce(function(a,b){
    if (a===b){
      tripleNum.push(a);
    }
  })
  if (tripleNum.length >= 3){
    console.log(tripleNum);
  } else {
    console.log("There wasnt a case of three straight triple numbers occuring");
  }

}

2 个答案:

答案 0 :(得分:2)

这也可以使用正则表达式完成:)

var testNumbers = function(num1){
  var stringOne = num1.toString();
  var regEx = /111|222|333|444|555|666|777|888|999|000/;

  if (regEx.test(stringOne)){
    console.log(stringOne.match(regEx)[0]);
  } else {
    console.log("There wasnt a case of three straight triple numbers occuring");
  }
}

答案 1 :(得分:1)

每当新数字等于过去的数字时,我会保留一个增加的计数器。如果那个计数达到三,我们就会恢复正常。否则,如果循环结束,我们返回false。例如:

function count3(arr) {
  // initialize a counter
  let count = 1
  
  // loop through the array, starting with the second
  // element, so we can compare it to the first
  for (let i = 1; i < arr.length; i++) {
  
    // does the count equal the previous?
    // if so increase it, otherwise set it back to 1
    count = arr[i] === arr[i - 1] ? count + 1 : 1 // <-- ternary operator
    // see if we're done
    if (count === 3) return true
  }
  // never reached three
  return false
}

// try it out
var arr = [3, 3, 4, 1, 5, 6, 3, 4, 3, 5, 6, 5]
console.log(count3(arr))

var arr = [3, 3, 4, 1, 5,5,5, 6, 3, 4, 3, 5, 6, 5]
console.log(count3(arr))

// make sure it works when array ends with three
var arr = [ 5, 6, 7, 3, 3, 3]
console.log(count3(arr))

// with strings too?
console.log(count3('34156335666'))