-1

我通过阅读 Eloquent JavaScript 来学习 JavaScript。我在本书网站提供的控制台上运行我的代码。我SyntaxError : Unexpect Identifier从以下代码中得到一个。请帮忙。

function absolute (n){
  if (n < 0)
    return -n;
  else
    return n;
}  

function average(x, y){
  return (x + y) / 2;
}


function isGoodEnough(x, guess){
  return (absolute(x - guess) < 0.0001);
}

function maybe(x, guess){
  if isGoodenough(x, guess){
    return guess;
  }
  else{
    return maybe(x, average(x, x/guess));
  }
}

function sqrt(x){
  return maybe(x, 1);
} 
4

6 回答 6

3

您在if声明中缺少括号:

if (isGoodEnough(x, guess)) {

您还拼错了函数名称,这将导致另一个错误。

于 2013-10-17T16:01:20.670 回答
2

if isGoodenough(x, guess){缺少括号:if(isGoodenough(x, guess)){

于 2013-10-17T16:00:45.533 回答
1

isGoodEnough 在 Maybe 函数中拼写错误。

function maybe(x, guess){
  if isGoodenough(x, guess){
    return guess;
  }
  else{
    return maybe(x, average(x, x/guess));
  }
}
于 2013-10-17T16:00:04.403 回答
1

你错过了括号

 if isGoodEnough(x, guess){
    return guess;
  }

应该

 if (isGoodEnough(x, guess)){
    return guess;
  }
于 2013-10-17T16:00:59.157 回答
1

if您需要在此条件周围加上括号:

function maybe(x, guess) {
    if (isGoodEnough(x, guess)) {   // Note extra parentheses
        ...

(您在这里也拼错了“isGoodEnough”。)

于 2013-10-17T16:01:15.450 回答
0

您需要在 if 条件和 else 周围加上括号。在 if 语句之后也使用括号来测试语句。应该看起来像

 function absolute (n){
  if (n < 0){
    return -n;
    }
  else {
    return n;
    }
  }  

 function average(x, y){
   return (x + y) / 2;
   }


 function isGoodEnough(x, guess){
   return (absolute(x - guess) < 0.0001);
   }

 function maybe(x, guess){
  if (isGoodEnough(x, guess)){
     return guess;
     }
  else{
     return maybe(x, average(x, x/guess));
     }
 }

  function sqrt(x){
   return maybe(x, 1);
  }
于 2013-10-17T16:20:43.557 回答