自定义Symbol.iterator方法产生死循环的原理?

在对象上使用自定义的Symbol.iterator方法会造成死循环?

产生死循环的原因是什么?

    var randoms = {

        [Symbol.iterator]: function (){

            return {

                next: function (){

                    return {value: Math.random().toFixed(2)};

                }

            };

        }

    };


    var randoms_pool = [];


    for(var n of randoms){

        randoms_pool.push(n);

        if(randoms_pool.length === 10) break; // 人为中断

    }


    console.log(randoms_pool);


一只甜甜圈
浏览 635回答 1
1回答

神不在的星期二

const randoms = {&nbsp; &nbsp; [Symbol.iterator]: function () {&nbsp; &nbsp; &nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; next: function () {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var r = Math.random();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if ( r < 0.9 )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return { value: r, done: false }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return { value: null, done: true }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}let randomsPool = [];for ( var random of randoms ) {&nbsp; &nbsp; randomsPool.push( random );}console.log( randomsPool )
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript