JS怎么遍历json数组
用 for in 循环遍历var str = '[{"name":"宗2瓜","num":"1","price":"122"},{"name":"宗呱呱","num":"1","price":"100"}]';var xqo = eval('(' + str + ')');for(var i in xqo){ alert(xqo[i].name);}
js怎么取list数组
可以用JS中对List、Map的遍历的方法
1.方法1
$.each(list2,function(index,items){
console.info(index+":"+items);
});
//遍历map
$.each(map_demo,function(key,value){
console.info("key: " + key + ", Value: " + value );
})
$.map()遍历List/map//遍历List
var new_list = $.map(list2,function(items,index){
return items+"!";
})
console.info(new_list);
//遍历map
$.map(map_demo,function(key,value){
console.log(key+":"+value);
});
小结:$.map()写法和$.each()类似,但对list的遍历时,参数顺序和$.each()是相反的,并且可以带返回值。对map的遍历和$.each()一样
2.for...in...遍历List/map//遍历map
for(var key in map_demo){
console.info(key+":"+map_demo[key]);
}
//遍历List
for(var index in list2){
console.info(index+":"+list2[index]);
}
小结:对于List来说,能不用for...in就不要用,效率低下。
3.forEach遍历Listlist2.forEach(function (element, index, array) {
console.info(element); //当前元素的值
console.info(index); //当前下标
console.info(array); //数组本身
});
小结:和for循环效率差不多。
在JavaScript中,我们可以使用下标来获取list数组中的元素。下标是从0开始的整数,它表示数组中元素的位置。
例如,如果我们有一个名为myArray的数组,我们可以使用myArray[0]来获取第一个元素,myArray[1]来获取第二个元素,以此类推。
我们还可以使用循环和条件语句来遍历数组并获取所需的元素。总之,在JavaScript中获取list数组的元素非常简单,只需要使用下标即可。
还没有评论,来说两句吧...