博客
关于我
for / forEach / each 循环详解
阅读量:275 次
发布时间:2019-03-01

本文共 1355 字,大约阅读时间需要 4 分钟。

for循环(使用比较局限,一般只用于循环数组)

var arr = ['zxx', 18, 'smart', 'good'];for(var i = 0, len = arr.length; i < len; i++){    console.log(i + '. ' + arr[i]);}// 0. zxx// 1. 18// 2. smart// 3. good

forEach循环(其中item为该索引下的值,index为索引,arr为数字本身,参数名可改变,但是顺序不能改变)

var arr = ['zxx', 18, 'smart', 'good'];arr.forEach(function(item,index,arr){    console.log(item);    console.log(index);    console.log(arr);});// zxx// 0// ["zxx", 18, "smart", "good"]// 18// 1// ["zxx", 18, "smart", "good"]// smart// 2// ["zxx", 18, "smart", "good"]// good// 3// ["zxx", 18, "smart", "good"]

each循环

jquery下的each方法有两种,一种为$('').each(),jquery对象方法,用于循环遍历jquery对象。一种为$.each()循环方法,用于循环遍历数组、对象。

第一种:$('').each()

<body>    <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>      <ul>        <li>li(1)</li>        <li>li(2)</li>        <li>li(3)</li>    </ul></body><script>$('li').each(function(i,item) {    console.log($(this).text());});</script>

第二种:$.each()

var arr = ['nick','freddy','mike','james'];var userMsg = {    nick: {	name: 'nick',	age: 18,	sex: '男'	    },    freddy: {	name: 'freddy',	age: 24,	sex: '男'    }	};$.each(arr,function(index,item){    console.log(index+'. '+item);});console.log('-----------分割线-----------');$.each(userMsg,function(key1,item1){    console.log(key1);    $.each(item1,function(key2,item2){	console.log(key2 + ': ' + item2);	    });});

你可能感兴趣的文章
Nginx
查看>>
nginx + etcd 动态负载均衡实践(三)—— 基于nginx-upsync-module实现
查看>>
nginx + etcd 动态负载均衡实践(二)—— 组件安装
查看>>
nginx + etcd 动态负载均衡实践(四)—— 基于confd实现
查看>>
Nginx + Spring Boot 实现负载均衡
查看>>
Nginx + uWSGI + Flask + Vhost
查看>>
Nginx - Header详解
查看>>
Nginx - 反向代理、负载均衡、动静分离、底层原理(案例实战分析)
查看>>
nginx 1.24.0 安装nginx最新稳定版
查看>>
nginx 301 永久重定向
查看>>
nginx css,js合并插件,淘宝nginx合并js,css插件
查看>>
Nginx gateway集群和动态网关
查看>>
Nginx Location配置总结
查看>>
Nginx log文件写入失败?log文件权限设置问题
查看>>
Nginx Lua install
查看>>
nginx net::ERR_ABORTED 403 (Forbidden)
查看>>
Nginx SSL私有证书自签,且反代80端口
查看>>
Nginx upstream性能优化
查看>>
Nginx 中解决跨域问题
查看>>
nginx 代理解决跨域
查看>>