简体   繁体   中英

Why does a object method not return a value?

In the following code, the function findById() does not actually return anything. The console.log() s fire and print as expected but the result is that the variable the function is being called to is undefined.

I have tried to change return value types, even simply putting return true; at the end with no conditional, but it always is undefined. To make sure I was not missing something simple I actually created a function that only returns a value istrue() . This actually works fine.

This is the object/method def

const database = {
    // List of authenticated characters
    characters: [],
    addCharacter: function(c) {
        this.characters.push(c);
    },
    findById: function(id) {
        console.log('Searching for character...');
        this.characters.forEach((c) => {
            if (c.id === id) {
                console.log('Found');
                console.log('cid: ' + c.id);
                console.log('id: ' + id);
                return true; // Never actually returns
            }
        });
    },
    istrue: function() {
        return true;
    }
};

and where it is being called

const find = database.findById(characterIdToFind);
console.log(typeof find); // always undefined
console.log(find); // always undefined

I expect there to be some kind of return value in at least one of the permutations of this function I have tried. There is never any change in the return value of the function, simply undefined .

The return statement inside a nested function return from function.

In this case you could use some() instead of forEach() because you can't break forEach .

findById: function(id) {
    console.log('Searching for character...');
    return this.characters.some(c => c.id === id)
}

If you want to get the object which matches the given condition that use find()

findById: function(id) {
    console.log('Searching for character...');
    return this.characters.find(c => c.id === id)
}

If you see in above both method we are returning c.id === id implicitly in each iteration but it doesn't return from outer function.

这是因为您尝试从forEach返回并且forEach不返回任何内容

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM