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

时间:2018-01-06 21:33:03

标签: javascript ecmascript-6

我有一个像这样的javascript对象writeInfo: "" selectObject: "TextGrid example" num = Get number of intervals: 2 #for the syllable tier for m from 1 to num syllable$ = Get label of interval: 2, m syllable_start = Get start time of interval: 2, m word = Get interval at time: 1, syllable_start word$ = Get label of interval: 1, word appendInfoLine: "'word$','syllable$'" endfor 5' 10" let Lila = { name: 'Lila', height: 我想使用next()

进行迭代

6 个答案:

答案 0 :(得分:5)

您可以使用迭代器为对象分配Symbol.iterator属性。

详细了解iteration protocolsiterator.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; }




答案 1 :(得分:3)

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

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

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

答案 2 :(得分:2)

这是答案

const Lila = {
name: 'Lila',
height: `5'10"`,
weight: 185,
[Symbol.iterator](){
  // use index to track properties 
    let index = 0;
    // get the properties of the object 
 let properties = Object.keys(this);

 // set to true when the loop is done 
 let  Done = false;
// return the next method, need for iterator 
return {
    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]};
 // increment index
       index++;
    return obj;
 }



}; 


}};

答案 3 :(得分:1)

简单方法

let Lila = { name: 'Lila', height: 8, weight: 185 ,
[Symbol.iterator]:function* () {
     for( i in obj){
     yield [i,obj[i]] ; 
}}}

答案 4 :(得分:0)

您可以使用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)

答案 5 :(得分:0)

你可以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);

相关问题