导航
对数据结构读取的一种方式,有序的,连续的,基于拉取的一种消耗数据的组织方式
let arr = [1,2,3,4];
console.log(arr);
var arr1 = [1,2,3,4,5];
var ite = arr1[Symbol.iterator]();
console.log(ite);
var arr1 = [1,2,3,4];
var ite = arr1[Symbol.iterator]();
console.log(ite.next());
console.log(ite.next());
console.log(ite.next());
console.log(ite.next());
console.log(ite.next());
console.log(ite.next());
var tArr = new Int8Array(5);
tArr[0] = 100;
function myIterator(arr) {
let index = 0;
return {
next() {
return index < arr.length
? { value: arr[index++], done: false }
: { value: undefined, done: true }
}
}
}
var iter = myIterator([1,2,3,4,5]);
console.log(iter.next());
console.log(iter.next());
console.log(iter.next());
console.log(iter.next());
console.log(iter.next());
console.log(iter.next());
var arr = [1,2,3,4];
for (let i of arr) {
console.log(i); // 获取值
}
for (let i in arr) {
console.log(i); // 获取下标
}
const obj = {
start: [8,6,1,2,3,4],
end: [5,6,7,2,3],
[Symbol.iterator]() {
let index = 0,
arr = [...this.start, ...this.end],
len = arr.length;
return {
next() {
return index < len ?
{ value: arr[index++], done: false } :
{ value: undefined, done: true }
}
}
}
}
for(let i of obj){
console.log(i);
}
const arr1 = [...obj]; // 部署了迭代器接口的对象可以使用...运算符
console.log(arr1);
var map = new Map(['a', 1], ['b', 2])
for(let [key, value] of map){
console.log(key, value)
}
var obj = {
a: 1,
b: 2,
c: 3,
[Symbol.iterator](){
let map = new Map();
// 转成map
for(let [key, value] of Object.entries(this)){
map.set(key, value);
}
// 转成数组
let mapEntries = [...map];
let nextIndex = 0;
return {
next: function(){
if(nextIndex < mapEntries.length){
return {
value: mapEntries[nextIndex ++],
done: false
}
}
return {
value: undefined,
done: true
}
}
}
}
}
for(let i of obj){
console.log(i)
}