简体   繁体   English

javascript中另一个函数中的函数

[英]Function within another function in javascript

I was trying to call another function inside function iseven(n):我试图在函数 iseven(n) 中调用另一个函数:

function iseven(n) {
    function remainder(n) {
        if (n%2==0) {
            return true;
        } else {
            return false;
        }
    }
}
console.log(iseven(4));

It returns undefined.它返回未定义。

a right way to do this:正确的方法是:

function a(x) {    // <-- function
  function b(y) { // <-- inner function
    return x + y; // <-- use variables from outer scope
  }
  return b;       // <-- you can even return a function.
}
console.log(a(3)(4));

nested functions JS 嵌套函数 JS

Try尝试

function iseven(n) { return n % 2 === 0; }

You want something more like this你想要更多这样的东西

function iseven(n)  { 
    if (n%2==0) { 
        return true; } 
    else { 
        return false; 
    } 
}

console.log(iseven(4));

And something a bit more succinct:还有一些更简洁的东西:

function isEven(n) {
   return n % 2 === 0;
}

Not quite sure why the original was structure that way..不太清楚为什么原来的结构是那样的..

Your Main function iseven() does not return anything.您的 Main 函数 iseven() 不返回任何内容。 Based on your code it should return false.根据您的代码,它应该返回 false。 Here's the fix:这是修复:

function iseven(n) { 
    function remainder(n) { 
        if (n%2==0) { 
            return true; 
        } 
        else { 
            return false; 
        } 
    }
    //iseven() should return something
    return false; 
}
console.log(iseven(4));

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

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