gpt4 book ai didi

javascript - 对于 Javascript,是什么阻止了现代实现不将参数视为真正的数组?

转载 作者:行者123 更新时间:2023-11-29 09:55:20 25 4
gpt4 key购买 nike

我认为这是一个古老的 Javascript 行为(Crockford 说这是一个设计错误),在函数内部,arguments 就像一个数组,除了它不是真正的数组,所以数组方法不能被调用:

function foo() { console.log(arguments.slice(1)) }   // won't work
foo(1,2,3);

我刚刚在最新的 Firefox 和 Chrome 上试过它,但它在两者上都不起作用。所以我们可能不得不使用

function foo() { console.log(Array.prototype.slice.call(arguments, 1)) }
foo(1,2,3);

但为什么不让 arguments 在现代 JavaScript 中成为一个真正的数组呢?可能不应该有任何依赖于 arguments 的程序不是真正的数组?现在不把它变成真正的数组的原因可能是什么?

我能想到的一个原因是,如果程序员开始将其视为数组,那么代码将无法在旧版浏览器中运行,但 ECMA-5 中的其他内容也无法在旧版浏览器中运行。

最佳答案

直到 ECMAScript 5 开发的后期,参数对象才继承所有 Array.prototype 方法。但 2009 年 9 月 TC39 批准的 ES5“最终草案”并没有这个特性。

2009 年 8 月,Apple 的 Oliver Hunt 将此发布到 es5-discuss 邮件列表

https://mail.mozilla.org/pipermail/es5-discuss/2009-August/003112.html

I implement the logic to make the Arguments object inherit from Array in WebKit last friday and it's quickly turned up a severe
incompatibility with Prototype.js ... This breaks at the very least a number of Apple sites and Nasa.gov -- ... Due to these site breakages, caused by a major compatibility problem
in a fairly major library it seems infeasible to attempt to retrofit
array like behaviour onto arguments.

TC39 的其余成员同意 Oliver 的评估,并从最终草案中删除了该功能。

也许,这样的代码已经从网络上消失得足够多,以至于今天提出的 ES5 解决方案仍然可以工作。然而,这并不重要,因为 ES6 中的剩余参数是解决问题的更好方法,并且是一种全新的语法功能,不会与现有代码存在任何向后兼容性问题。

关于javascript - 对于 Javascript,是什么阻止了现代实现不将参数视为真正的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13184799/

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