jquery筛选数组之grep、each、inArray、map的用法及遍历json对象
grep
<scripttype='text/javascript'src="/jquery.js"></script>
<scripttype="text/javascript">
$().ready(
function(){
vararray=[1,2,3,4,5,6,7,8,9];
varfilterarray=$.grep(array,function(value){
returnvalue>5;//筛选出大于5的
});
for(vari=0;i<filterarray.length;i++){
alert(filterarray[i]);
}
for(keyinfilterarray){
alert(filterarray[key]);
}
}
);
</script>
each
<scripttype='text/javascript'src="/jquery.js"></script>
<scripttype="text/javascript">
$().ready(
function(){
varanObject={one:1,two:2,three:3};//对json数组each
$.each(anObject,function(name,value){
alert(name);
alert(value);
});
varanArray=['one','two','three'];
$.each(anArray,function(n,value){
alert(n);
alert(value);
}
);
}
);
</script>
inArray
<scripttype='text/javascript'src="/jquery.js"></script>
<scripttype="text/javascript">
$().ready(
function(){
varanArray=['one','two','three'];
varindex=$.inArray('two',anArray);
alert(index);//返回该值在数组中的键值,返回1
alert(anArray[index]);//valueistwo
}
);
</script>
map
<scripttype='text/javascript'src="/jquery.js"></script>
<scripttype="text/javascript">
$().ready(
function(){
varstrings=['0','1','2','3','4','S','6'];
varvalues=$.map(strings,function(value){
varresult=newNumber(value);
returnisNaN(result)?null:result;//isNaN:isNotaNumber的缩写
}
);
for(keyinvalues){
alert(values[key]);
}
}
);
</script>
遍历json对象:
<script>
varjson=[{dd:'SB',AA:'东东',re1:123},{cccc:'dd',lk:'1qw'}];
for(vari=0,l=json.length;i<l;i++){
for(varkeyinjson[i]){
alert(key+':'+json[i][key]);
}
}
</script>
遍历json对象
有如下json对象:
varobj={”name”:”冯娟”,”password”:”123456″,”department”:”技术部”,”sex”:”女”,”old”:30};
遍历方法:
for(varpinobj){
str=str+obj[p]+’,';
returnstr;
}