简体   繁体   English

使用匿名 function 索引 JavaScript 会给出错误:“未定义”

[英]Indexing JavaScript with anonymous function gives an error: "Undefined"

My problem is to retreive 'A', 'B', 'C' or 'D', if the first letter of my passed string s, belongs to {a,e,i,o,u} or {b,c,d,f,g} or {h,j,k,l,m} or other remaining, respectively.我的问题是检索'A','B','C'或'D',如果我传递的字符串s的第一个字母属于{a,e,i,o,u}或{b,c, d,f,g} 或 {h,j,k,l,m} 或其他剩余的,分别。 I am trying to achieve the same like this:我试图达到这样的效果:

function getLetter(s){
        let letter = 'ABCD'[findIndex(s[0])];
        return letter;
    }
function findIndex(t){
        var a = Number.parseInt("aeioubcdfghjklmnpqrstvwxyz".indexOf(t)/5);
        //console.log(a);
        if (a<3){
            return a;
        }
        else{
            return 3;
        }
    }

And it worked.它奏效了。 But when I tried to reduce the number of lines using an anonymous function, I can't get my function executed.但是当我尝试使用匿名 function 减少行数时,我无法执行我的 function。 I know I have a silly error, as I new to programming.我知道我有一个愚蠢的错误,因为我是编程新手。 What is wrong with my code?我的代码有什么问题? with something like this:像这样:

let getLetter = s =>'ABCD'[function(){
        var a = Number.parseInt("aeioubcdfghjklmnpqrstvwxyz".indexOf(s[0])/5);
        console.log("anonymous function executed");
        if (a<3){
            return a;
        }
        else{
            return 3;
        }
    }]
My output is: undefined

Thanks!谢谢!

It's because in your original code you are executing findIndex() , but in your second code you are simply using the anonymous function itself as index, you are not executing it.这是因为在您的原始代码中您正在执行findIndex() ,但在您的第二个代码中您只是使用匿名 function 本身作为索引,您没有执行它。

 let getLetter = s =>'ABCD'[function(){ var a = Number.parseInt("aeioubcdfghjklmnpqrstvwxyz".indexOf(s[0])/5); console.log("anonymous function executed"); if (a<3){ return a; } else{ return 3; } }()] console.log(getLetter("a"));

in your case you only write the function defenition.在您的情况下,您只需编写 function 定义。 to run a function you need to add ().要运行 function,您需要添加 ()。 so just add () after the defenition.所以只需在定义后添加()。

 let getLetter = s =>'ABCD'[function(){ var a = Number.parseInt("aeioubcdfghjklmnpqrstvwxyz".indexOf(s[0])/5); console.log("anonymous function executed"); if (a<3){ return a; } else{ return 3; } }()]; console.log(getLetter('a'));

In the first example, you called your findIndex method, but in the second one, you just defined the function , without calling it.在第一个示例中,您调用了findIndex方法,但在第二个示例中,您只是定义了function ,而没有调用它。

You have to solutions to fix it:你必须解决它:

  1. to use IIFE ( Immediately Invoked Function Expression ):使用IIFE立即调用 Function 表达式):

where you define and call your method, like what your trying to do here, check the documentation .您在哪里定义和调用您的方法,例如您在此处尝试执行的操作,请查看文档

 let getLetter = s =>'ABCD'[(function(){ var a = Number.parseInt("aeioubcdfghjklmnpqrstvwxyz".indexOf(s[0])/5); console.log("anonymous function executed"); if (a<3){ return a; } else{ return 3; } })()]; console.log(getLetter('e'))

  1. define findIndex as a seperated function :findIndex定义为单独的function

Which makes your code clearer.这使您的代码更清晰。

 let getLetter = s =>'ABCD'[_findIndex(s)]; let _findIndex = letter => { var a = Number.parseInt("aeioubcdfghjklmnpqrstvwxyz".indexOf(letter[0])/5); console.log("anonymous function executed"); if (a<3){ return a; } else{ return 3; } }; console.log(getLetter('e'))

You just pass the reference of function, you didn't execute it.你只是传递了 function 的引用,你没有执行它。 you can add () immediately after the function ends to run it like this:您可以在 function 结束后立即添加()以像这样运行它:

 let getLetter = s =>'ABCD'[function(){ var a = Number.parseInt("aeioubcdfghjklmnpqrstvwxyz".indexOf(s[0])/5); console.log("anonymous function executed"); if (a<3){ return a; } else{ return 3; } }()] console.log(getLetter('test'));

But I highly recommend not to do that, because it's harder to read, understand, maintain, and develop when time passes.但我强烈建议不要这样做,因为随着时间的推移,它会更难阅读、理解、维护和开发。 the more important than decrease code lines is it to be human-readable, like Martin Fowler say比减少代码行更重要的是它是人类可读的,就像Martin Fowler说的那样

Any fool can write code that a computer can understand.任何傻瓜都可以编写计算机可以理解的代码。 Good programmers write code that humans can understand.优秀的程序员编写人类可以理解的代码。

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

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