gpt4 book ai didi

javascript - 函数之间的简单给出错误?

转载 作者:行者123 更新时间:2023-11-30 07:02:06 25 4
gpt4 key购买 nike

我已经完成了这个非常简单的代码:

Number.prototype.between = function(a,b){
return this >= a && this < b ? 1 : 0;
};

但是在测试的时候:

5.between(1,10);

给我这个错误:

Uncaught SyntaxError: Unexpected token ILLEGAL(…)
InjectedScript._evaluateOn @ VM225:875
InjectedScript._evaluateAndWrap @ VM225:808
InjectedScript.evaluate @ VM225:664

我做错了什么?

最佳答案

JavaScript 引擎正在尝试将 5. 解析为 float ,并且由于 . 之后的标记不是有效数字,因此它因 SyntaxError 而失败。

要解决这个问题,您可以

  1. 在数字后面留一个空格

    console.log(5 .between(1, 10));
    // 1
  2. 使用圆括号明确表示 5 本身是一个表达式

    console.log((5).between(1, 10));
    // 1
  3. 像这样使用双点

    console.log(5..between(1, 10));
    // 1

PS:避免修改内置函数的原型(prototype)。您始终可以构建效用函数。

关于javascript - 函数之间的简单给出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34750715/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com