jQuery教程之$.each() - 遍历json和数组

来源:互联网 发布:Windows怎么截屏长图 编辑:程序博客网 时间:2024/05/17 20:58

遍历json数据

$.each()方法有两个参数,第一个参数传递要遍历的数据,可以是数组也可以是json。第二个参数是一个Function

Function可以传递两个参数:如果要遍历的数据是json时,第一个参数为json数据的key,第二个参数为json数据的value

<script>    var json = {        'width' : '20px' ,        'height' : '30px' ,        'border-radius' : '4px'    };    $.each(json , function(key  , value){         console.log('当前的键是:' + key + ",当前的值是:" + value );    });</script>

最后我们会在控制台看到如下输出结果:

当前的键是:width,当前的值是:20px
当前的键是:height,当前的值是:30px
当前的键是:border-radius,当前的值是:4px

Function可以传递两个参数:如果要遍历的数据是数组时,第一个参数为数组数据的下标,第二个参数为数组数据的value

var arr = ['a','b','c'];$.each( arr , function( index , value){    console.log( '当前的下标是:' + index + ",当前的值是:" + value);});

最后我们会在控制台看到如下输出结果:

当前的下标是:0,当前的值是:a
当前的下标是:1,当前的值是:b
当前的下标是:2,当前的值是:c

0 0
原创粉丝点击