我正在尝试返回与授权===管理员或授权===访客匹配的所有元素,但没有成功
这就是我到目前为止所拥有的。 Jsfiddle
var otherStuff = {};
courses = [
{ index: ['', 'overview'], moduleId: 'overview', title: 'overview', nav: 1 , authorize: ["sellers", "taxi"]},
{ index: 'rating', moduleId: 'rating', title: 'rating', nav: 3},
{ index: 'example', moduleId: 'example', title: 'example', nav: 5, authorize: ["Visitor", "Administrator"] },
{ index: 'apple', moduleId: 'apple', title: 'apple', nav: 6, authorize: ["User", "Administrator"] },
]
var resultSet = $.grep(courses, function (element, index) {
// return all element with authorize === Administrator or authorize === Visitor;
});
console.log(JSON.stringify(resultSet))
有人可以帮我吗?
最佳答案
我的两个解决方案都可以防止任何变量泄漏到您的闭包中,并且不需要任何库。自执行函数使您可以用任何类型的授权替换文字数组 ["Administrator", "Visitor"]。
ECMA 5 也是函数式编程的一个很好的例子。接受的答案不起作用,因为它缺乏针对多个身份验证类型进行测试的能力。
JSFIDDLE:http://jsfiddle.net/FcFDG/3/
var acceptedTypes = ["Administrator", "Visitor"];
// ECMA 5
var resultSetA = (function(authTypes){
return courses.filter(function(crs){
return crs && crs.authorize
&& crs.authorize.indexOf && authTypes.some(function(authType){
return ~crs.authorize.indexOf(authType);
});
});
})(acceptedTypes);
console.log(JSON.stringify(resultSetA));
//Compatibility with all browsers (ECMAScript 3):
var resultSetB = (function(authTypes){
var results = [], i, j, k, works;
for(i=0; i<courses.length; i++){
if(courses[i]&&courses[i].authorize&&courses[i].authorize.length){
works = false;
for(j=0; j<courses[i].authorize.length; j++){
for(k=0; k<authTypes.length; k++){
works = works || courses[i].authorize[j] === authTypes[k];
}
}
if(works)
results.push(courses[i]);
}
}
return results;
})(acceptedTypes);
console.log(JSON.stringify(resultSetB));
关于javascript - 我如何使用authorize === Administrator返回数组中的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22058127/