TypeError:.next()不是函数

时间:2020-08-07 14:09:32

标签: javascript iterator typeerror

dataArr = []
let element;

function Users()
 {

    let url = 'https://randomuser.me/api'
    fetch(url).then((response) =>{
        return response.json();
    }).then((data) =>{
         
        dataArr.push(data['results']);
    })
}



for (let i = 0; i < 5; i++) {

    Users()
}

console.log(dataArr);


function profileIter(values) {

    let nextIndex = 0;
    if(nextIndex < values.length){
        return {
            value: values[nextIndex++],
            done: false
        }
    }
    else{
        return {
            done: true
        }
    }}


const CVIter = profileIter(dataArr);


console.log(CVIter.next().value);

运行此命令后,我收到一条错误消息

CVIter.next()不是函数

check this image out

1 个答案:

答案 0 :(得分:0)

您的profileIter函数返回的是IteratorResult对象,而不是迭代器,因此next()函数不存在。

如果要获得迭代器,则必须使profileIter像这样的生成器:


function * profileIter(values) {
    for (let nextIndex = 0; nextIndex < values.length; ++nextIndex){
        yield values[nextIndex];
    }
}

或让您的函数返回迭代器

function profileIter(values) {
    let nextIndex = 0;

    return {
        next: () => {
            if (nextIndex < values.length){
                return {
                    value: values[nextIndex++],
                    done: false
                };
            }

            return {
                done: true
            };
        },
    };
}