浅谈JavaScript中的for循环语句的使用
Admin 2021-09-24 群英技术资讯 920 次浏览
这篇文章主要给大家分享的是JavaScript中for循环的内容,对于for循环大家应该都是比较熟悉的吧,下面小编给大家总结了JavaScript中的三种for循环语句使用,对新手学习和理解for循环有一定的帮助,感兴趣的朋友就继续往下看吧。
这大概是应用最广的循环语句了吧,简单实用,且大多数时候性能还是在线的,唯一的缺点大概就是太普通,没有特色,导致很多人现在不愿用它。
const array = [4, 7, 9, 2, 6]; for (let index = 0; index < array.length; index++) { const element = array[index]; console.log(element); } // 4, 7, 9, 2, 6
for...in 语句可以以任意顺序遍历一个对象的除 Symbol 以外的可枚举属性。
const temp = {name: "temp"}; function Apple() { this.color = 'red'; } Apple.prototype = temp; const obj = new Apple(); for (const prop in obj) { console.log(`obj.${ prop } = ${ obj[prop] }`); } // obj.color = red // obj.name = temp
如果你只要考虑对象本身的属性,而不是它的原型,那么使用 getOwnPropertyNames() 或执行 hasOwnProperty() 来确定某属性是否是对象本身的属性。
const temp = {name: "temp"}; function Apple() { this.color = 'red'; } Apple.prototype = temp; const obj = new Apple(); for (const prop in obj) { if (obj.hasOwnProperty(prop)) { console.log(`obj.${ prop } = ${ obj[prop] }`); } } // obj.color = red
当然,也可以用来遍历数组。
const arr = [1, 2, 3, 4, 5]; for (const key in arr) { console.log(key) } // 0,1,2,3,4
使用 for...in 可以遍历数组,但是会存在以下问题:
所以一般不建议使用 for...in 来遍历数组。
for...of 语句在可迭代对象(包括 Array,Map,Set,String,TypedArray,arguments 对象等等)上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句。
const array = ['a', 'b', 'c']; for (const element of array) { console.log(element); } // a // b // c
for...of 和 for...in 的区别:
Object.prototype.objCustom = function () { }; Array.prototype.arrCustom = function () { }; let iterable = [3, 5, 7]; iterable.foo = 'hello'; for (const key in iterable) { console.log(key); // logs 0, 1, 2, "foo", "arrCustom", "objCustom" } // 0, 1, 2, "foo", "arrCustom", "objCustom" for (const key of iterable) { console.log(key); } // 3, 5, 7
使用 for...of 遍历 Map 结构:
let nodes = new Map(); nodes.set("node1", "t1") .set("node2", "t2") .set("node3", "t3"); for (const [node, content] of nodes) { console.log(node, content); } // node1 t1 // node2 t2 // node3 t3
可以看出,使用 for...of 遍历 Map 结构还是挺方便的,推荐使用!
关于JavaScript中for循环就介绍到这,上文介绍和总结了JS种的三种for循环语句的使用,有需要的朋友可以了解看看,对理解for循环有一定的帮助。想要了解更多JavaScript中for循环的内容,大家可以关注群英网络其它相关文章。
文本转载自脚本之家
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
实现方法:1、给按钮绑定点击事件并指定一个事件处理函数;2、在事件处理函数中利用“document.getElementById(出现元素对象).style.display="block";”语句设置点击按钮元素显示即可。
javascript中的math.random()是用来生成随机数的,其使用语法如“Math.floor(Math.random() * 10 + 1);”,该语句能在连续整数中取得一个随机数。
浅谈访问vue实例this指针的相关知识,一些朋友可能会遇到这方面的问题,对此在下文小编向大家来讲解一下,内容详细,易于理解,希望大家阅读完这篇能有收获哦,有需要的朋友就往下看吧!
这篇文章主要为大家详细介绍了js+Html实现表格可编辑操作,能动态添加删除行,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本篇文章给大家带来了关于javascript的相关知识,其中主要整理了异步与回调的基本概念的相关问题,同步,一般指按照预定的顺序依次执行任务,只有当上一个任务完成后,才开始执行下一个任务,异步,与同步相对应,异步指的是让CPU暂时搁置当前任务,先处理下一个任务,当收到上个任务的回调通知后,再返回上个任务继续执行,下面一起来看一下,希望对大家有帮助。
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008