Javascript对象如何与for语句进行迭代?

时间:2016-03-05 20:50:13

标签: javascript debugging ecmascript-6 iterator for-of-loop

我想设置var width = window.innerWidth; var height = window.innerHeight; var nodes = [{"id":"1","name":"a"},{"id":"2","name":"b"}]; var links = [{"source":0,"target":1}]; var svg = d3.select("body").append("svg"); svg.attr("width", width); svg.attr("height", height); svg.append("svg:g"); var tree = d3.layout.tree(); tree.size([width, height]); tree.nodes(nodes); tree.links(links); 属性,以便使用options[Symbol.iterator]语句迭代我创建的简单对象:

for...of

但是这段代码给了我以下错误:

options = {
  male: 'John',
  female: 'Gina',
  rel: 'Love'
};


for(let p of options){
  console.log(`Property ${p}`);
};

如何在上面的简单对象上设置正确的迭代器函数?

  
    

解决了

  
 array.html:72 Uncaught TypeError: options[Symbol.iterator] is not a function

我可以在我的对象上使用 // define the Iterator for the options object options[Symbol.iterator] = function(){ // get the properties of the object let properties = Object.keys(this); let count = 0; // set to true when the loop is done isDone = false; // define the next method, need for iterator let next = () => { // control on last property reach if(count >= properties.length){ isDone = true; } return {done:isDone, value: this[properties[count++]]}; } // return the next method used to iterate return {next}; }; 语句现在可迭代:

for...of

3 个答案:

答案 0 :(得分:23)

要使用for...of循环,您应该使用[Symbol.iterator]键为对象定义适当的迭代器。

以下是一种可能的实施方式:

let options = {
  male: 'John',
  female: 'Gina',
  rel: 'Love',
  [Symbol.iterator]: function * () {
    for (let key in this) {
      yield [key, this[key]] // yield [key, value] pair
    }
  }
}

但是,在大多数情况下,最好使用普通for...in循环迭代对象。

或者,您可以使用Object.keysObject.valuesObject.entries(ES7)将对象转换为可迭代数组。

答案 1 :(得分:10)

如果您不想使用生成器语法,可以使用另一种方式定义迭代器函数。

    var options = {
        male: 'John',
        female: 'Gina',
        rel: 'Love',
        [Symbol.iterator]: function () {
            var self = this;
            var values = Object.keys(this);
            var i = 0;
            return {
                next: function () {
                    return {
                        value: self[values[i++]],
                        done: i > values.length
                    }
                }
            }
        }
    };

    for (var p of options) {
        console.log(`Property ${p}`);
    }

答案 2 :(得分:3)

普通对象(在这种情况下为options)在ES6中不可迭代。您需要为对象定义迭代器或执行以下操作:

for(let k of Object.keys(options)) {
  console.log(`Property ${k}, ${options[k]}`);
};