生成键,值并以{value:..,key:..,done:..}格式完成的方法

时间:2017-12-10 15:50:57

标签: javascript ecmascript-6

.next()方法返回一个具有两个属性的对象,即value和done。有没有一个方法可以返回键和值并完成?这是代码:

onActivityCreated

此代码的输出为:

const james = {
    name: 'James',
    height: `5'10"`,
    weight: 185,
    [Symbol.iterator]:function*(){   
       for(let key of Object.keys(this)) {
          yield  this[key]; 
       }
    }
};

const iterator = james[Symbol.iterator]();

console.log(iterator.next()); 
console.log(iterator.next()); 
console.log(iterator.next());

预期产出:

{ value: 'James', done: false }
{ value: '5\'10"', done: false }
{ value: 185, done: false }

2 个答案:

答案 0 :(得分:1)

您将在生成器中获得的最接近的是自己生成对象

$return = $_POST; 
if(isset($return)) {    
    $return["model_id"] = $return;
    echo json_encode($return);
    exit;
}

yield {key: key, value: this[key]};

答案 1 :(得分:0)

您可以创建自己的迭代包装函数,如下所示:



const james = {
    name: 'James',
    height: `5'10"`,
    weight: 185,
};

// Custom iterator wrapper
const iterate = (obj) => {
  function* iter(){   
       for(let key of Object.keys(obj)) {
          yield {key: key, value: obj[key]}; 
       }
  }
  return () => {
    const r = iter().next();
    return {key: r.value.key, value: r.value.value, done: r.done};
  }
}


const next = iterate(james);

console.log( next() ); 
console.log( next() ); 
console.log( next() );