如何在Javascript中创建可迭代对象

i7uaboj4  于 2023-01-11  发布在  Java
关注(0)|答案(6)|浏览(109)

我有一个这样的javascript对象

let Lila = { 
  name: 'Lila', 
  height: `5'10"`,
  weight: 185
}

我想用next()迭代它

7vhp5slm

7vhp5slm1#

您可以使用迭代器将Symbol.iterator属性赋给对象。
阅读更多关于在iteration protocols中使用iterator.next的信息。

let lila = { name: 'Lila', height: '5\'10"', weight: 185 };

lila[Symbol.iterator] = function* () {
    var k;
    for (k in this) {
        yield [k, this[k]];
    }
};

var iterator = lila[Symbol.iterator]();

console.log(iterator.next()); // get the first of a sequence of values

console.log([...lila]);       // get all key/values pairs
.as-console-wrapper { max-height: 100% !important; top: 0; }
djmepvbi

djmepvbi2#

这就是答案

const Lila = {
    name: 'Lila',
    height: `5'10"`,
    weight: 185,
    [Symbol.iterator]() {
        let index = 0; // use index to track properties 
        let properties = Object.keys(this); // get the properties of the object 
        let Done = false; // set to true when the loop is done 
        return { // return the next method, need for iterator 
            next: () => {
                Done = (index >= properties.length);
                // define the object you will return done state, value eg Lila ,key eg 
                //name
                let obj = {
                    done: Done,
                    value: this[properties[index]],
                    key: properties[index]
                };
                index++; // increment index
                return obj;
            }
        };
    }
};
sczxawaw

sczxawaw3#

为什么你需要一个迭代器或生成器?保持简单,只需迭代对象...

const lila = { name: 'Lila', height: '5\'10"', weight: 185 };

for (key in lila) { console.log(lila[key]) }
eivnm1vs

eivnm1vs4#

你可以convert an object to an iterable (Array) with Object.entries

let Lila = {
  name: 'Lila',
  height: 5.10,
  weight: 185
};
let iterableLila = Object.entries(Lila);
console.log(iterableLila);
erhoui1w

erhoui1w5#

你可以使用Object.keys()迭代一个对象的键,然后用一个迭代器函数封装它:

function makeIterator(obj) {
    let keys = Object.keys(obj);
    let current_index = 0;

    return {
       next: function() {
           return current_index < keys.length ?
               {value: obj[keys[current_index++]], done: false} :
               {done: true};
       }
    };
}

你可以这样使用它:

let Lila = { name: 'Lila', height:5'10",
    weight: 185}
let iterator = makeIterator(Lila)
console.log(iterator.next().value)
console.log(iterator.next().value)
console.log(iterator.next().value)
htzpubme

htzpubme6#

尝试 * 以下 *:

const lila = {
  name: "lila",
  height: "5'10",
  weight: 185,
  [Symbol.iterator] () {
    let step = 0;
    let properties = Object.keys(this); 
    return{ 
      next(){
        return{
          value: properties[step],
          done: step++ === properties.length
        }
      }
    }
  }
}for (let prop of lila){console.log(prop)}

相关问题