JS each遍历对象
发表时间: 2020-06-03 11:09:58 | 浏览次数:
原来整整有一年没发布新文章了,今天发一篇最近比较常用到的一个知识点吧:each遍历。
each遍历一维数据:
var arr1 = ["aaa", "bbb", "ccc" ]; $.each(arr1, function(key, val){ console.log(key +": "+ val); });
输出结果:0: aaa 1: bbb 2: CCC
each遍历二维数据:
var arr2 = [['a', 'aa', 'aaa'], ['b', 'bb', 'bbb'], ['c', 'cc', 'ccc']]; $.each(arr2, function(key, val){ console.log("一维:"+ key +": "+ val); $.each(val, function(key2, val2){ console.log("二维:"+ key2 +": "+ val2); }); });
输出结果:
一维: 0: a,aa,aaa
二维: 0: a 二维: 1: aa 二维: 2: aaa
一维: 1: b,bb,bbb
二维: 0: b 二维: 1: bb 二维: 2: bbb
一维: 2: c,cc,ccc
二维: 0: c 二维: 1: cc 二维: 2: ccc
each遍历JSON数据:
var arr3 = {id:1, name:"小明", age:3};
$.each(arr3, function(key, val) {
console.log(key +": "+ val);
});
输出结果:id: 1 name: 小明 age: 3
each遍历二维JSON数据:
var arr4 = [{id:1, name:"小明", age:5}, {id:2, name:"小王", age:6}];
$.each(arr4, function(key, val) {
console.log(key +" id:"+ val.id);
console.log(key +" name:"+ val.name);
console.log(key +" age:"+ val.age);
console.log("------------");
});
输出结果:
0 id:1
0 name:小明
0 age:5
------------
1 id:2
1 name:小王
1 age:6
------------
each遍历form表单数据:
<form id="eachForm" class="form-horizontal" role="form">
<div class="form-group">
<label for="firstname" class="col-sm-2 control-label">姓名</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="firstname" id="firstname" placeholder="请输入姓名">
</div>
</div>
<div class="form-group">
<label for="phone" class="col-sm-2 control-label">手机号码</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="phone" id="phone" placeholder="请输入手机号码">
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-2 control-label">邮箱</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="email" id="email" placeholder="请输入邮箱">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" class="btn btn-default">提交</button>
</div>
</div>
</form>
<script>
$(".btn").click(function(){
var params = $("#eachForm").serializeArray();
$.each(params, function() {
console.log(this.name +": "+ this.value);
});
});
</script>
输出结果:
firstname: 小明
phone: 1888888888
email: each@1rfun.com
上一篇:Bootstrap模态框(Modal)的运用
下一篇:CSS div里的内容垂直居中和水平居中