博客
关于我
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 集成Zipkin服务链路追踪
查看>>
nginx 集群配置方式 静态文件处理
查看>>
Nginx+Django-Python+BPMN-JS的整合工作流实战项目
查看>>
Nginx+Keepalived+LVS集群实战
查看>>
Nginx+Keepalived实现简单版高可用主备切换
查看>>
nginx+mysql+redis+mongdb+rabbitmq 自动化部署脚本
查看>>
nginx+php的搭建
查看>>
nginx+tomcat+memcached
查看>>
Nginx+Tomcat实现动静分离
查看>>
nginx+Tomcat性能监控
查看>>
nginx+uwsgi+django
查看>>
nginx+vsftp搭建图片服务器
查看>>
Nginx-http-flv-module流媒体服务器搭建+模拟推流+flv.js在前端html和Vue中播放HTTP-FLV视频流
查看>>
nginx-vts + prometheus 监控nginx
查看>>
Nginx/Apache反向代理
查看>>
Nginx: 413 – Request Entity Too Large Error and Solution
查看>>
nginx: [emerg] getpwnam(“www”) failed 错误处理方法
查看>>
nginx: [emerg] the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx/conf/nginx.conf:
查看>>
nginx:Error ./configure: error: the HTTP rewrite module requires the PCRE library
查看>>