簡體   English   中英

如何檢查一個Javascript數組,該數組至少包含一個以特定文本開頭的值(例如ROLE_)

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

我有下面的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;
        }

您已經很接近了,但是對於您想要的內容,不需要使用下划線:

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數組

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM