for in
for...in
语句用于遍历对象。
for (keys in objectName){}
let star={
name:'James',
age:35,
chaimpion:3
}
for( let keys in star){
console.log(star[keys])
}
for of
for...of
语句在可迭代对象(包括 Array
,Map
,Set
,String
,TypedArray
,arguments 对象等等)上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句
// 数组
let arr1=[2,3,5,34,23]
for(let i of arr1){
console.log(i);
}
//字符串
let str= 'james'
for(let i of str){
console.log(i)
}
// map
let map= new Map([["name",'kobe'],["age",41]]);
for(let i of map){
console.log(i)
}
Array.prototype.forEach()
forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。forEach() 对于空数组是不会执行回调函数的。
语法:
array.forEach(function(currentValue, index, arr), thisValue)
参数 | 描述 |
---|---|
function(currentValue, index, arr) | 必需。 数组中每个元素需要调用的函数。 函数参数:currentValue必需有,当前元素。index可选,当前元素的索引值。arr*可选,当前元素所属的数组对象。 |
thisValue | 可选。传递给函数的值一般用 "this" 值。 如果这个参数为空, "undefined" 会传递给 "this" 值 |
let arr=[2,4,6,43,32,23]
arr.forEach(function(ele)
{
console.log(ele)
})
let arr=[1,2,4,32,23,35]
let sum =0;
arr.forEach(function(value)
{
sum+=value;
});
console.log(sum)