检查参数中的交替数字和布尔值

Check for alternating numbers and booleans in arguments

我希望能够检查参数对象的特定交替对象类型,如下所示:

number, boolean, number, boolean ==> 1, true, 2, false....etc

我尝试了这个(在我将参数对象变成数组之后):

var check = args.some ( function (val, i) {
  var type = typeof(val);
  return i % 2 == 0 ? type === 'number' : type === 'boolean';
});

用some方法可以吗?

您可以检查 Array#every 和类型数组。

The every method executes the provided callback function once for each element present in the array until it finds one where callback returns a falsy value. If such an element is found, the every method immediately returns false. Otherwise, if callback returns a truthy value for all elements, every returns true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.

function isAlternate(v, i) {
    console.log(i, v, ['number', 'boolean'][i % 2], typeof v === ['number', 'boolean'][i % 2]);
    return typeof v === ['number', 'boolean'][i % 2];
}

console.log([1, 2, 3].every(isAlternate));
console.log([1, true, 2, false].every(isAlternate));
console.log([null, null].every(isAlternate));
.as-console-wrapper { max-height: 100% !important; top: 0; }

function check(array) {
    return array.every(function (v, i) {
        if (typeof v === ['number', 'boolean'][i % 2]) {
            return true;
        }
        console.log('wrong item found at', i);
    });
}

console.log(check([1, 2, 3]));
console.log(check([1, true, 2, false]));
console.log(check([null, null]));
.as-console-wrapper { max-height: 100% !important; top: 0; }

使用 ES6,你可以使用 Array#findIndex

function getWrongIndex(array) {
    return array.findIndex((v, i) => typeof v !== ['number', 'boolean'][i % 2]);
}

console.log(getWrongIndex([1, 2, 3]));           //  1
console.log(getWrongIndex([1, true, 2, false])); // -1 no wrong index found
console.log(getWrongIndex([null, null]));        //  0