第一句子网 - 唯美句子、句子迷、好句子大全
第一句子网 > for each in 和 for in 和for of

for each in 和 for in 和for of

时间:2019-04-06 14:31:24

相关推荐

for each in 和 for in 和for of

for Each

从ES5开始 Javascript内置了forEach方法 用来遍历数组,但是存在一个局限,就是你不能中断循环(使用break语句或使用return语句);

例:

let arr = ['a', 'b', 'c', 'd']

arr.forEach(function (val, idx, arr) {

console.log(val + ', index = ' + idx) // val是当前元素,index当前元素索引,arr数组

console.log(arr)

})

输出结果:

a, index = 0

(4) ["a", "b", "c", "d"]

b, index = 1

(4) ["a", "b", "c", "d"]

c, index = 2

(4) ["a", "b", "c", "d"]

d, index = 3

(4) ["a", "b", "c", "d"]

for…in

for-in循环实际是为循环”enumerable“对象而设计的,for - in 也可用来循环数组,但一般并不推荐

例:

let obj = {a: '1', b: '2', c: '3', d: '4'}

for (let o in obj) {

console.log(o) //遍历的实际上是对象的属性名称 a,b,c,d

console.log(obj[o]) //这个才是属性对应的值1,2,3,4

}

for…of

它是ES6中新增加的语法

例如:循环一个数组let arr = ['China', 'America', 'Korea'] for (let o of arr) { console.log(o) //China, America, Korea }

但是它并不能循环一个普通对象,但是可以循环一个拥有enumerable属性的对象。如果我们按对象所拥有的属性进行循环,可使用内置的Object.keys()方法,如果我们按对象所拥有的属性值进行循环,可使用内置的Object.values()方法

例如循环一个字符串:

letstr = 'love'

for(let o of str){

console.log(o)// l,o,v,e

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。