检查数组中的部分匹配

检查数组中的部分匹配

本文介绍了检查数组中的部分匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JavaScript数组,其中包含一些在请求创建用户帐户时无法使用的单词。

I have a JavaScript array that contains some words that cannot be used when requesting user accounts to be created.

我正在尝试循环请求的帐户并检查他们反对一个字过滤器。如果它们包含任何单词,则该值将移动到无效帐户数组。

I am trying to loop over the accounts requested and check them against a word filter. If they contain any of the words, the value is moved to an array of "Invalid Accounts".

// Create our arrays
var blacklist = ["admin", "webform", "spoof"];
var newAccounts = ["[email protected]", "[email protected]", "[email protected]"];
var invalidAccounts = [];

// I need to check if any of the new accounts have matches to those in the blacklist.
// [email protected] would need to be pushed into the invalidAccounts array because it
// contains the word admin. Although interweb contains the word web, it does not contain
// the full word, webform, so should be ignored.

// Loop over the blacklist array
for(var x = 0; x < blacklist.length; x++){
  if(blacklist[x].indexOf(newAccounts) > -1){
    alert(blacklist[x] + " is in the blacklist array");
    // Push the newAccounts value into the invalidAccounts array since it contains
    // a blacklist word.
  } else {
    alert('no matches');
  }
}

我需要在上面的代码中更改为它是否与提到的部分字符串匹配?

What do I need to change in the above code to have it match the partial strings such as mentioned?

上述代码的小提示:

推荐答案

您可能不需要全部使用但这应该是有帮助的:

You probably won't need to use all of this but it should be helpful none the less:

var blacklist = ["admin", "webform", "spoof"];
var newAccounts = ["[email protected]", "[email protected]", "[email protected]"];
var invalidAccounts = [];

// transform each email address to an object of the form:
// { email: string, valid: boolean }
var accountObjects = newAccounts.map(function (a) {
    return { email: a, valid: true };
});

// loop over each account
accountObjects.forEach(function (account) {
    // loop over the blacklisted terms
    blacklist.forEach(function (blacklisted) {
        // check to see if your account email address contains a black listed term
        // and set the valid property accordingly
        account.valid = account.email.search(blacklisted) === -1;
    });
});

// filter accountObjects, validAccounts will now contain an array of valid objects
var validAccounts = accountObjects.filter(function (a) {
    return a.valid;
});

// back to the original type of a string array
var validEmailAddresses = validAccounts.map(function (a) {
    return a.email;
});

这篇关于检查数组中的部分匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 13:47