不能在另一个函数的相关代码中使用函数变量吗?

Can you not use function variables inside another function's associated code?

本文关键字:函数 变量 另一个 不能 代码      更新时间:2023-09-26

在Codecademy[1]的代码练习中,它要求您对一个变量进行立方,我可以很容易地使用:

// Accepts a number x as input and returns its square
function square(x) {
  return x * x;
}
// Accepts a number x as input and returns its cube
function cube(x) {
  return x * x * x;
}
cube(7);

我的问题是立方体函数,为什么当我使用以下代码时,我会得到NaN错误:

function cube(x) {
  return x * square;
}

[1] http://www.codecademy.com/courses/functions_in_javascript/0 !/运动/1

try:

你错过了(x)

function cube(x) {
  return x * square(x);
}

应该是

function cube(x) {
    return x * square(x);
}

x * square将尝试将x与导致问题的函数相乘

在您的代码中,square被解析为一个函数。要获得返回值,您需要调用函数,而不仅仅是引用

function cube(x) {
  return x * square(x);
}

当进行乘法或除法运算时,首先将两个参数都转换为数字。函数没有合理的转换,所以它们被转换为NaN。

Number(function(){}) //gives NaN

如果你用NaN乘以任何数你也会得到NaN

2 * NaN
1 * (function(){}) //also gives NaN since the function is converted to that

解决方案(正如许多人提到的)是乘以x的平方,而不是乘以平方函数本身。

x * square(x)