方便json对象迭代可以用…object
示例图
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>json对象或数组遍历重写iterator接口3</h1>
</body>
<script>
function iteratorUtil() {
let index = -1;
let _this = this;
if (_this instanceof Array) {
return {
next() {
let len = _this.length;
//console.log(len);
index++;
//console.log(index);
return index < len ? {
value: _this[index],
done: false
} : {
value: _this[index],
done: true
};
}
};
} else {
let keys = Object.keys(_this);
let len = keys.length;
return {
next() {
index++;
let key = keys[index];
return index < len ? {
value: _this[key],
done: false
} : {
value: _this[key],
done: true
};
}
};
}
}
let user = {
username : '张三',
age : 123,
sex: '妖',
eat(){
console.log('吃西瓜');
}
};
//json对象迭代
Object.prototype[Symbol.iterator] = iteratorUtil;
Array.prototype[Symbol.iterator] = iteratorUtil;
for(const item of user) {
console.log(item);
}
console.log('%c-------------------------------------------','color:red');
console.log(...user);
console.log('%c-------------------------------------------','color:red');
let user2 = [...user,...user]
//json对象 转数组
console.log(user2);
console.log('%c-------------------------------------------','color:red');
//数组迭代
let arr = [1,2,3,4];
for (const item of arr) {
console.log(item);
}
console.log('%c-------------------------------------------','color:red');
console.log(...arr);
</script>
</html>