一、数组,对象示例
对于字符串: 字符串本质上是字符数组
对于对象数组: 就是数组,里面每个成员都是对象
let Str = 'ab'
let Arr = ['11', '22']
let Obj = {
id: 001,
name: 'aa'
}
// 对象数组
let ArrObj = [
{ id: '001', name: 'aaa' },
{ id: '002', name: 'bbb' }
]
二、for-in
// for- in : i 是 index (在数组、字符串中) 或者 key (在对象中)
for (const i in Str) {
console.log(i, ' - ', Str[i]);
// 0 - a
// 1 - b
}
for (const i in Arr) {
console.log(i, ' - ', Arr[i]);
// 0 - 11
// 1 -22
}
for (const i in Obj) {
console.log(i, ' - ', Obj[i]);
// id - 1
// name - aa
}
for (const i in ArrObj) {
console.log(i, ' - ', ArrObj[i],
ArrObj[i].id, ArrObj[i].name);
// 0 - { id: '001', name: 'aaa' } 001 aaa
// 1 - { id: '002', name: 'bbb' } 002 bbb
}
三、for-of
:注意不能应用于对象
// for -of : i是元素 , 且 xxx[i] === undefined
for (const i of Str) {
console.log(i);
// a
// b
}
for (const i of Arr) {
console.log(i);
// 11
// 22
}
// for (const i of Obj) { 对象没有迭代器Iterator }
for (const i of ArrObj) {
console.log(i, ' - ', i.id, i.name)
// { id: '001', name: 'aaa' } - 001 aaa
// { id: '002', name: 'bbb' } - 002 bbb
}
四、for-of 遍历 Map、Set
:之所以不能 for-in 是因为 map和set 都没有index
:可以用 forEach
const set = new Set(['1', '2', '1', '3']) // 这个不演示了
const map = new Map([['1', 'one'], ['2', 'two']]);
map.set('3','three')
map.get('3') // three
map.delete('3')
console.log(map);
// Map(2) { '1' => 'one', '2' => 'two' }
for (const i of map) {
console.log(i, ' --- ', i[0], i[1]);
// [ '1', 'one' ] --- 1 one
// [ '2', 'two' ] --- 2 two
}
for (const i of map.keys()) {
console.log(i, map.get(i));
// 1 one
// 2 two
}
for (const i of map.values()) {
console.log(i);
// one
// two
}
五、forEach
:只用于数组。字符串转数组:常用是 Str.spilt(“”)
Arr.forEach((val,i) => {
// 1~3个形参,按 value index array(就是Arr) 排列,一般就只用一个value
console.log(i,' - ',val);
});