请问在JS中如何在对象中用push添加一个新的属性然后遍历
var arr={a:1,b:2,c:3}; arr.d = 4; // a: 1, b: 2, c: 3, d: 4 for(var i in arr) { alert(i + ": " + arr[i]); }
js中item遍历函数获取元素的数量
item只是数组或集合遍历中的元素的变量,例如:
var arr = [1, 2, 3]
for(var item in arr) { // item遍历数组时为数组的下标,遍历对象时为对象的key值
console.log(item); // 0, 1, 2
};
$(selector).each(function(item,element))
jQuery通用的全局遍历方法$.each()用法实例
1.test.json文件代码:
[
{
"username": "张三",
"content": "沙发."
},
{
"username": "李四",
"content": "板凳."
},
{
"username": "王五",
"content": "地板."
}
]
2.html代码:
<p>
<input type="button" id="send" value="加载"/>
</p >
<div >已有评论:</div>
<div id="resText" ></div>
3.jQuery代码:
<script src="jquery-1.3.1.js" type="text/javascript"></script>
<script type="text/javascript">
/*
1.$.each()是jquery的一个通用的遍历方法,可用于遍历对象和数组
2.$.each()函数不同于jquery对象的each()方法,它是一个全局函数,不操作jquery对象,而是以一个数组或者对象作为第一个参数,以一个回调函数作为第二个参数。回调函数拥有两个参数:第一个参数为对象的成员或数组的索引,第二个参数为对应变量或内容
*/
$(function(){
$('#send').click(function() {
$.getJSON('test.json', function(data) {
$('#resText').empty();
var html = '';
$.each( data , function(commentIndex, comment) {
html += '<div ><h6>' + comment['username'] + ':</h6><p >' + comment['content'] + '</p ></div>';
})
$('#resText').html(html);
})
})
})
</script>
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循环效率差不多。
还没有评论,来说两句吧...