在String.prototype.slice()中,.slice(0,-0)和.slice(0,+0)应该输出相同的结果吗?

In String.prototype.slice(), should .slice(0,-0) and .slice(0,+0) output the same result?

我在代码高尔夫游戏中尝试优化字符串复数时遇到了这个怪癖。我有想法将字符串写成复数形式,然后使用 substr 有条件地切断最后一个字符:

var counter = 1;
var myText = counter + " units".substr(0, 6-(counter===1));

很好 - 它可以满足我的要求。但是看着 MDN docs for String.prototype.slice(),我想我已经找到了一种方法,通过使用负零作为函数的第二个参数来使它 更短,。来自文档:

endSlice

Optional. The zero-based index at which to end extraction. If omitted, slice() extracts to the end of the string. If negative, it is treated as sourceLength + endSlice where sourceLength is the length of the string (for example, if endSlice is -3 it is treated as sourceLength - 3).

var myText = counter + " units".slice(0,-(counter===1));

counter 等于 1 时,计算结果为 .slice(0,-1),这将从字符串中截取最后一个字母,否则计算结果为 .slice(0,-0),根据docs 应该意味着从正在操作的字符串的长度中减去 0 个字符。

碰巧,-0 被 String.prototype.slice 视为与 +0 相同。我想知道这是否是一种约定,将 -0 视为与 +0 相同(我知道,例如,-0 === +0 的计算结果为 true)。我想看看 String.prototype.substr,但是 +0 和 -0 应该在该函数中以相同的方式处理。

有没有人对此有更深入的了解?语言设计中是否有一些基本约定表明,虽然带符号的零是一种语言功能,但应忽略它,除非在某些情况下(如 1/-0)?

tl;dr我很咸,我不能通过切片.[=24=来开玩笑赢得代码高尔夫]

从数学的角度来看,没有负零。正数是任何大于零的数,负数是任何小于零的数。零不是那些。所以我猜你描述的行为是正确的。

A real number may be either rational or irrational; either algebraic or transcendental; and either positive, negative, or zero.

https://en.wikipedia.org/wiki/Real_number

虽然,因为在编程中我们使用浮点数,它是实数的近似值,所以有 -0 的概念,它可以表示太接近零而无法用其他方式表示的负数- http://www.johndcook.com/blog/2010/06/15/why-computers-have-signed-zero/


关于你的javascript,你可以这样写:

var counter = 1;
var myText = counter + " unit" + (counter > 1 ? "s" : "");