如何检查包含至少一个以特定文本开头的值的 Javascript 数组(例如 ROLE_)

How to check a Javascript array that contains at least one value that starts with a particular text (eg. ROLE_)

我有下面的 javascript 'underscore' 代码,它检查给定的 USER_ROLES 是否至少有一个 VALID_ROLES。如果是 returns true 否则为 false。 它工作正常。

但我想重构它,以便删除硬编码角色 VALID_ROLES 并想检查是否至少有一个以 ROLE_ 开头的角色。怎么办?

            // Function to check if least one valid role is present
        var USER_ROLES = ['ROLE_5'];

        function hasAnyRole(USER_ROLES) {

            var VALID_ROLES = [ 'ROLE_1', 'ROLE_2', 'ROLE_3', 'ROLE_4' ];

            for (var i = 0; i < USER_ROLES.length; i++) {
                if (_.contains(VALID_ROLES, USER_ROLES[i])) {
                    console.log("Found a valid role, returning true.");
                    return true;
                }
            }
            console.log("No valid role found, returning false.");               
            return false;
        }

你已经很接近了,但是对于你想要的,不需要使用下划线:

for (var i = 0; i < USER_ROLES.length; i++) {
    if (typeof USER_ROLES[i].indexOf == "function" && USER_ROLES[i].indexOf("ROLE_") > -1) {
        console.log("Found a valid role, returning true.");
        //return true;
    }
}

用这个。不需要下划线,你可以使用 .some array

USER_ROLES.some(function(value){
 return value.substring(0, 5) === "ROLE_";
});
var index, value, result;
for (index = 0; index < USER_ROLES.length; ++index) {
    value = USER_ROLES[index];
    if (value.substring(0, 5) === "ROLE_") {
        // You've found it, the full text is in `value`.
        // So you might grab it and break the loop, although
        // really what you do having found it depends on
        // what you need.
        result = value;
        break;
    }
}

// Use `result` here, it will be `undefined` if not found