indexOf到some()javaScript

时间:2019-02-08 00:47:46

标签: javascript

我正在尝试将下面的函数转换为使用.some()方法,但我不知道这是如何工作的。我已经阅读了MDN文档。 谁能帮我吗?

function guessRepeatValidate(userGuess) {
    let passed = true;
    if (guessArchive.indexOf(userGuess) > -1) {
        passed = false;
    }
    return passed;

}

3 个答案:

答案 0 :(得分:0)

这里是如何转换。

let guessArchive = ['test', 'some'];

function guessRepeatValidate(userGuess) {
    return !guessArchive.some(i => i===userGuess);
}

console.log(guessRepeatValidate('test'));

console.log(guessRepeatValidate('blah'));

答案 1 :(得分:0)

const guessRepeatValidate = (userGuess, guessArchive) => !guessArchive.some(i => i === userGuess);

const guessArchive = ['one', 'two', 'three'];

console.log(guessRepeatValidate('one', guessArchive));

console.log(guessRepeatValidate('four', guessArchive));

答案 2 :(得分:0)

对于这种问题,可以接受的做法是使用includes,但是,如果您真的想使用some

function guessRepeatValidate(userGuess) {
    return !guessArchive.some(e => e == userGuess);
}