gpt4 book ai didi

javascript - JavaScript 是否有未定义的行为?

转载 作者:行者123 更新时间:2023-12-03 12:45:29 25 4
gpt4 key购买 nike

JavaScript 是否具有未定义的行为(类似于 C),或者它是否完全由规范定义且具有确定性?

请注意,我正在丢弃实现错误和规范分歧。我也在丢弃 Math.random() 之类的东西和 Date.now() .

是否有一段 JavaScript 代码的行为未完全由 JavaScript 规范确定,并且因此具有“未定义的行为”?

最佳答案

规范中有很多东西明确地留给了实现。尤其是当涉及到主机对象时,可能会有很多怪癖。与宿主对象无关的示例:

15.1 The Global Object

The values of the [[Prototype]] and [[Class]] internal properties of the global object are implementation-dependent.



15.1.2.2 parseInt (string , radix)

[If there are too many significant digits] mathInt may be an implementation-dependent approximation to the mathematical integer value that is represented by Z in radix-R notation.



15.3.4.2 Function.prototype.toString

An implementation-dependent representation of the function is returned.


几乎所有的日期解析/字符串化算法都是 依赖于实现 , 这包括 toLocaleString , toString , parseDate构造函数。

15.4.4.11 Array.prototype.sort (comparefn) - likely the best example:

If comparefn is not undefined and is not a consistent comparison function for the elements of this array, the behaviour of sort is implementation-defined.

[…] If proto is not null and there exists an integer j such that all of the conditions below are satisfied then the behaviour of sort is implementation-defined:

  • obj is sparse (15.4)
  • 0 ≤ j < len

The behaviour of sort is also implementation defined if obj is sparse and any of the following conditions are true:

  • The [[Extensible]] internal property of obj is false.
  • Any array index property of obj whose name is a nonnegative integer less than len is a data property whose [[Configurable]] attribute is false.

The behaviour of sort is also implementation defined if any array index property of obj whose name is a nonnegative integer less than len is an accessor property or is a data property whose [[Writable]] attribute is false.


最突出的是:

Perform an implementation-dependent sequence of calls […]



15.5.4.9 String.prototype.localeCompare (that)

The two Strings are compared in an implementation-defined fashion



15.5.4.11 String.prototype.replace[In replacement symbols, if the number is greater than the number of groups], the result is implementation-defined.


我将在此处停止列出,您可以通过规范搜索。其他值得注意的地方可能是 toLocaleString方法,或 Math 返回的依赖于实现的近似值方法。

关于javascript - JavaScript 是否有未定义的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14863430/

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