python中for不能遍历的数据类型_一文带你理解:可以迭代大部分数据类型的 for…of 为什么不能遍历普通对象?...

for…of 及其使用

我们知道,ES6 中引入 for...of 循环,很多时候用以替代 for...in 和 forEach() ,并支持新的迭代协议。for...of 允许你遍历 Array(数组), String(字符串), Map(映射), Set(集合),TypedArray(类型化数组)、arguments、NodeList对象、Generator等可迭代的数据结构等。for...of语句在可迭代对象上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句。

for...of的语法:for (variable of iterable) {

// statement

}

// variable:每个迭代的属性值被分配给该变量。

// iterable:一个具有可枚举属性并且可以迭代的对象。

常用用法{

// 迭代字符串

const iterable = 'ES6';

for (const value of iterable) {

console.log(value);

}

// Output:

// "E"

// "S"

// "6"

}

{

// 迭代数组

const iterable = ['a', 'b'];

for (const value of iterable) {

console.log(value);

}

// Output:

// a

// b

}

{

// 迭代Set(集合)

const iterable = new Set([1, 2, 2, 1]);

for (const value of iterable) {

console.log(value);

}

// Output:

// 1

// 2

}

{

// 迭代Map

const iterable = new Map([["a", 1], ["b", 2], ["c", 3]]);

for (const entry of iterable) {

console.log(entry);

}

// Output:

// ["a", 1]

// ["b", 2]

// ["c", 3]

for (const [key, value] of iterable) {

console.log(value);

}

// Output:

// 1

// 2

// 3

}

{

// 迭代Arguments Object(参数对象)

function args() {

for (const arg of arguments) {

console.log(arg);

}

}

args('a', 'b');

// Output:

// a

// b

}

{

// 迭代生成器

function* foo(){

yield 1;

yield 2;

yield 3;

};

for (let o of foo()) {

console.log(o);

}

// Output:

// 1

// 2

// 3

}

Uncaught TypeError: obj is not iterable// 普通对象

const obj = {

foo: 'value1',

bar: 'value2'

}

for(const item of obj){

console.log(item

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值