简体   繁体   English

为什么对象方法不返回值?

[英]Why does a object method not return a value?

In the following code, the function findById() does not actually return anything. 在以下代码中,函数findById()实际上未返回任何内容。 The console.log() s fire and print as expected but the result is that the variable the function is being called to is undefined. console.log()按预期方式触发并打印,但结果是调用该函数的变量未定义。

I have tried to change return value types, even simply putting return true; 我试图更改返回值类型,甚至只是简单地将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() . 为了确保我没有错过简单的事情,我实际上创建了一个仅返回值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 . 函数的返回值永远不会有任何变化,只是undefined

The return statement inside a nested function return from function. 嵌套函数内部的return语句从函数返回。

In this case you could use some() instead of forEach() because you can't break forEach . 在这种情况下,可以使用some()代替forEach()因为您不能破坏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() 如果要获取与给定条件匹配的对象,请使用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. 如果您在上面的两种方法中都看到过,则在每次迭代中我们都会隐式返回c.id === id ,但它不会从外部函数return

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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