简体   繁体   English

array.forEach之后的回调函数

[英]Callback function after array.forEach

I have a function that compares an array of 2 strings ... eg ['snookums', 'snook'] , which looks to return true if all of the letters in the 2nd string appear in the first, so in this instance, it should return true. 我有一个比较2个字符串数组的函数...例如['snookums', 'snook'] ,如果第二个字符串中的所有字母都出现在第一个字符串中,则看起来返回true,因此在这种情况下,它应该返回true。

I have it working with a for loop: 我有一个for循环的工作:

function mutation(arr) {
    for (var i = 0; i < arr[1].length; i++) {
        if (arr[0].indexOf(arr[1][i]) === -1) {
            return false;
        }
    }
    return true;
    });
}

However, I would like to get this working in a better way, ultimately with forEach. 但是,我希望最终可以通过forEach更好地工作。 I have it console logging out false if it comes across a letter which doesn't match, but I am wondering will this work, how will I return true if it gets to the end of the forEach and indexOf() returns true for each letter. 我有安慰登出false ,如果它遇到一个字母不匹配,但我想知道将这项工作,我将如何返回true ,如果它到达的终点forEachindexOf()返回true对每个字母。

function mutation(arr) {
return arr.pop()
    .split('')
    .forEach(function(letter) {
        console.log(arr[0].indexOf(letter) === -1);
    });
}
console.log(mutation(["snookums", "for"]));

Does that make sense? 那有意义吗?

Thank you 谢谢

forEach is not a "better" way. forEach 不是 “更好”的方式。 What you are looking for is the every method : 您正在寻找的是every方法

function mutation(arr) {
    return arr[1].split("").every(function(letter) {
        return arr[0].indexOf(letter) !== -1;
    });
}

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

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