簡體   English   中英

在 javascript 迭代器中遞增計數器

[英]Incrementing counter in a javascript iterator

我正在嘗試在 js 迭代器上增加一個計數器。 自然地,索引被重新初始化。 想知道在 js 迭代器中將計數器保持在范圍內而不重新初始化索引變量的標准做法是什么。

一個想法是將索引作為客戶內部的全局屬性,但不知何故,我覺得這不是一個好方法,這是代碼:

 console.log(`Custom Iterator`) let store = { customers: [{ id: 1, name: `Ali`, food: [1, 3], }, { id: 2, name: `Usman`, food: [2] }], foods: [{ id: 1, name: `Waffles` }, { id: 2, name: `Fries` }, { id: 3, name: `Pizza` }] } let Customers = { [Symbol.iterator]: () => { return { index: 0, next: () => { let index = 0; console.log(index); while (index <= store.customers.length) { return { value: store.customers[index], done: false } index++; } return { done: true } } } } } let iterator = Customers[Symbol.iterator](); console.log(iterator.next().value); console.log(iterator.next().value); console.log(iterator.next().value); /* for (let customer of Customers) { console.log(customer); } */

當調用[Symbol.iterator] ,您可以創建一個索引變量,其作用域僅在該迭代器運行時:

 console.log(`Custom Iterator`) let store = { customers: [{ id: 1, name: `Ali`, food: [1, 3], }, { id: 2, name: `Usman`, food: [2] }], foods: [{ id: 1, name: `Waffles` }, { id: 2, name: `Fries` }, { id: 3, name: `Pizza` }] } let Customers = { [Symbol.iterator]: () => { let index = 0; return { next: () => { const value = store.customers[index++]; return { value: value, done: !value }; } }; } } let iterator = Customers[Symbol.iterator](); console.log(iterator.next().value); console.log(iterator.next().value); console.log(iterator.next().value); /* for (let customer of Customers) { console.log(customer); } */

在這種特殊情況下,由於您想迭代一個數組,您也可以只生成該數組 - 最好避免在可能的情況下與手動索引混淆:

 console.log(`Custom Iterator`) let store = { customers: [{ id: 1, name: `Ali`, food: [1, 3], }, { id: 2, name: `Usman`, food: [2] }], foods: [{ id: 1, name: `Waffles` }, { id: 2, name: `Fries` }, { id: 3, name: `Pizza` }] } let Customers = { [Symbol.iterator]: function*() { yield* store.customers; } } let iterator = Customers[Symbol.iterator](); console.log(iterator.next().value); console.log(iterator.next().value); console.log(iterator.next().value); /* for (let customer of Customers) { console.log(customer); } */

這就是我解決問題的方式 atm

 let Customers = { index: 0, [Symbol.iterator]: () => { return { next: () => { while (Customers.index < store.customers.length) { let customer = store.customers[Customers.index++]; customer.food = store.foods.filter(food => customer.food.indexOf(food.id) > -1) // console.log(Array.isArray(customer.food) ? 'array' : object); return { value: customer, done: false } } return { done: true } } } } }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM