简体   繁体   English

在js数组中查找顺序值

[英]finding sequential values in js array

What's wrong with this code?这段代码有什么问题?

I'm experimenting with a simple card game to see if one has a straight.我正在尝试一个简单的纸牌游戏,看看是否有顺子。

The logic is to just check if the next value in the array is the current value + 1逻辑是只检查数组中的下一个值是否是当前值 + 1

 let arr = [ [ 'd', 13 ], [ 'f', 12 ], [ 'z', 11 ], [ 'd', 10 ], [ 'd', 9 ] ]; arr = arr.sort((a,b) => a[1] - b[1]); const isSeq = arr => { for (let i = 0; i < arr.length - 1; i++) { console.log(arr[i][1]+1, arr[i+1][1]) if (arr[i][1]+1 !== arr[i+1][1]) { return false; } else { return true; } } } isSeq(arr);

You need to remove the else part, because this would exit the function even if true in the first iteration.您需要删除 else 部分,因为即使在第一次迭代中为真,这也会退出函数。

 let arr = [[ 'd', 13 ], [ 'f', 12 ], [ 'z', 11 ], [ 'd', 10 ], [ 'd', 9 ]]; arr = arr.sort((a, b) => a[1] - b[1]); const isSeq = arr => { for (let i = 0; i < arr.length - 1; i++) { console.log(arr[i][1] + 1, arr[i + 1][1]); if (arr[i][1] + 1 !== arr[i + 1][1]) { return false; } } return true; }; console.log(isSeq(arr));

You're quick returning after the first check, one way or the other.在第一次检查后,你很快就回来了,不管怎样。

if (arr[i][1]+1 !== arr[i+1][1]) {
    return false;
} else {
    return true;
}

You should return after all the checks have been done:您应该在完成所有检查后返回:

for (let i = 0; i < arr.length - 1; i++) {
    console.log(arr[i][1]+1, arr[i+1][1])
    if (arr[i][1]+1 !== arr[i+1][1]) {
        return false;
    }
  }
  return true;

You can also do this with Array#every() :你也可以用Array#every()做到这一点:

 let arr = [ ['d', 13], ['f', 12], ['z', 11], ['d', 10], ['d', 9] ]; arr = arr.sort((a, b) => a[1] - b[1]); function isSeq(data) { return data.every((num, i) => (i === data.length - 1) || (num[1] === (data[i + 1][1] - 1))); } console.log(isSeq(arr));

This first checks if the index is the last, and if not makes sure that the current element is equal to array[i+1]-1这首先检查索引是否是最后一个,如果不是,则确保当前元素等于array[i+1]-1

Instead if else with return , you can use break :相反, if else带有return ,您可以使用break

Take the first value as the current and iterate the remainder of the input.将第一个值作为当前值并迭代输入的其余部分。 Compare each entry to the current.将每个条目与当前条目进行比较。 If the sequence is broken, break from the loop.如果序列中断,则中断循环。 Before moving to the next entry, set this as one as the new current.在移动到下一个条目之前,将其设置为新的当前条目。

 let arr = [ [ 'd', 13 ], [ 'f', 12 ], [ 'z', 11 ], [ 'd', 10 ], [ 'd', 9 ] ]; arr = arr.sort((a,b) => a[1] - b[1]); const isSeq = arr => { let isStraight = true let current = arr[0][1] for (let i = 1; i < arr.length; i++) { if (arr[i][1] !== current + 1) { isStraight = false break } current = arr[i][1] } return isStraight } console.log(isSeq(arr))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM