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

时间:2016-06-09 10:21:41

标签: javascript underscore.js underscore.string.js

我有以下javascript'下划线'检查给定USER_ROLES是否至少有一个VALID_ROLES的代码。如果是则返回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;
        }

3 个答案:

答案 0 :(得分:1)

你非常接近,但是对于你想要的东西,没有必要使用下划线:

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;
    }
}

答案 1 :(得分:0)

使用它。不需要下划线就可以使用.some数组

USER_ROLES.some(function(value){
 return value.substring(0, 5) === "ROLE_";
});

答案 2 :(得分:0)

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