ElJ*_*ste 7 javascript standards ecma
这是mentionned在ECMAScript标准在这里说:
...这些功能不被视为核心ECMAScript语言的一部分.编写新的ECMAScript代码时,程序员不应使用或假设存在这些特性和行为.除非实现是Web浏览器的一部分,或者需要运行与Web浏览器相同的旧ECMAScript代码,否则不鼓励ECMAScript实现实现这些功能.
MDN上还有一个红色警告:String.prototype.substr()MDN doc
有谁知道为什么(ECMAScript标准说)程序员不应该使用或假设存在String.prototype.substr?
小智 21
的主要优点substr是您可以指定负的起始位置!做同样的事情substring是可怕的。
我已将此声明添加为顶级ambient.d.ts文件中的环境声明:
interface String {
/**
* Gets a substring beginning at the specified location and having the specified length.
* (deprecation removed)
* @param from The starting position of the desired substring. The index of the first character in the string is zero.
* @param length The number of characters to include in the returned substring.
*/
substr(from: number, length?: number): string;
}
Run Code Online (Sandbox Code Playgroud)
我觉得substr非常有用。指定字符串的长度通常比指定字符串的结束索引要简洁得多。如果substr真的从浏览器或 Node.js JavaScript 支持中删除,我怀疑我们中的许多人无论如何都会简单地通过猴子补丁substr恢复存在。
因为它从未成为标准化语言的一部分.它根本不在ECMAScript 1或2规范中,只出现在B.2.2节("附加属性")中的ECMAScript 3中(以及类似附件中的后续版本),其中说:
ECMAScript的一些实现包括一些标准本机对象的附加属性.这个非规范性附件提出了这些属性的统一语义,而没有使这个属性或它们的语义成为本标准的一部分.
而且,substr在很大程度上是多余的substring,但第二个论点具有不同的含义,以及与slice.
从实用的角度来说,如果你找到一个没有提供它的主流JavaScript引擎,我会感到惊讶.