2016-06-09 6 views
0

주어진 USER_ROLES에 적어도 하나의 VALID_ROLES가 있는지 확인하는 아래 자바 스크립트 '밑줄'코드가 있습니다. true의 경우는 true, 그렇지 않은 경우는 false를 돌려줍니다. 잘 작동합니다.특정 텍스트 (예 : ROLE_)로 시작하는 하나 이상의 값을 포함하는 자바 스크립트 배열을 확인하는 방법

하지만 하드 코딩 된 역할 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; 
     } 
+0

해보십시오 underscore.any 사용할 수 없습니다 (USER_ROLES, 기능 (역할을) {0 (role.substring 반환, 5) === "ROLE_";}) – netoctone

+0

@netoctone 고마워요. any() 및 some() 밑줄 함수가 동일합니까? – Jay

+0

예 http://underscorejs.org/#some 또한 이전 브라우저를 지원할 필요가없는 경우 ES 5.1 Array.prototype.some http://www.ecma-international.org/ecma를 사용할 수 있습니다. -262/5.1/# sec-15.4.4.17 – netoctone

답변

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

감사합니다. – Jay

0

사용이. 밑줄의 필요 당신이 K2661에 배열

USER_ROLES.some(function(value){ 
return value.substring(0, 5) === "ROLE_"; 
}); 
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