jquery筛选数组之grep、each、inArray、map的用法及遍历son对象(转)

grep [传入的参数为返回bool类型的函数]
<script type='text/javascript' src="/jquery.js"></script>
<script type="text/javascript">
$().ready(
    function(){
        var array = [1,2,3,4,5,6,7,8,9];
        var filterarray = $.grep(array,function(el,index){
            return el > 5;//筛选出大于5的
        });
        for(var i=0;i<filterarray.length;i++){
            alert(filterarray[i]);
        }
        for (key in filterarray){
            alert(filterarray[key]);
        }
    }
);
</script>

 
each[传入的参数为处理过程]
<script type='text/javascript' src="/jquery.js"></script>
<script type="text/javascript">
$().ready(
    function(){
        var anObject = {one:1,two:2,three:3};//对json数组each
        $.each(anObject,function(index,el) {
            alert(index);
            alert(el);
        });
        var anArray = ['one','two','three'];
        $.each(anArray,function(index,el){
            alert(index);
            alert(el);
        }
        );
    }
);
</script>

inArray[用于返回某个值在数组中的下标]
<script type='text/javascript' src="/jquery.js"></script>
<script type="text/javascript">
$().ready(
    function(){
        var anArray = ['one','two','three'];
        var index = $.inArray('two',anArray);
        alert(index);//返回该值在数组中的键值,返回1
        alert(anArray[index]);//value is two
    }
);
</script>

map[带有返回值类型的函数]
<script type='text/javascript' src="/jquery.js"></script>
<script type="text/javascript">
$().ready(
    function(){
        var strings = ['0','1','2','3','4','S','6'];
        var values = $.map(strings,function(value){
                var result = new Number(value);
                return isNaN(result) ? null:result;//isNaN:is Not a Number的缩写
            }
        );
        for (key in values) {
            alert(values[key]);
        }
    }
);
</script>

 

遍历json对象:
<script>
var json = [{dd:'SB',AA:'东东',re1:123},{cccc:'dd',lk:'1qw'}];
for(var i=0,l=json.length;i<l;i++){
    for(var key in json[i]){
        alert(key+':'+json[i][key]);
    }
}
</script>

遍历json对象
有如下 json对象:
var obj ={”name”:”冯娟”,”password”:”123456″,”department”:”技术部”,”sex”:” 女”,”old”:30};
遍历方法:
for(var p in obj){
    str = str+obj[p]+’,';
    return str;
}


 借此补补课,each是(index,el)

其他的两个是el index。

posted on 2016-08-14 10:38  漫思  阅读(1762)  评论(0编辑  收藏  举报

导航