【问题标题】:What is the purpose of +- on a Javascript number?Javascript 数字上 +- 的目的是什么?
【发布时间】:2021-03-26 21:15:25
【问题描述】:

我最近遇到了一些类似这样的代码:

const element = document.getElementById("myId")
const rect = element.getBoundingClientRect()

const height = +-(rect.height / 1)

首先,除以 1 是什么意思?其次,+- 是做什么的?

我将该逻辑放入 Fiddle 中,它似乎翻转了括号中的符号(从正到负,从负到正)。但是,如果我想翻转一个标志,我为什么不直接做-(myvariable)

关于除以 1,rect.height 的类型似乎已经是具有浮点精度的数字,并且除法运算符也是浮点除法,因此我们不尝试生成 int 或任何东西。

我只是需要一些帮助来尝试理解它在做什么。

编辑:代码在这里找到:Check if element is partially in viewport

【问题讨论】:

  • 您在哪里找到了该代码?
  • 修改原帖。
  • +-(null / 1); 创建-0
  • 我经常在 javascript 代码中发现人们使用 (+"string") 来转换为一个数字,-/ 类似——所以这里的用户可能只是......全部使用了它们.

标签: javascript


【解决方案1】:

使用division / 会将两个操作数隐式转换为数字:

const str = "10.5"

const division = str / 1;

console.log(division);
console.log(typeof division);

使用a unary minus - 将隐式转换操作数更改其符号:

const str = "10.5";
const minusStr = -str;

console.log(minusStr);
console.log(typeof minusStr);


const negativeNum = -3;
const minusNegativeNum = -negativeNum;

console.log(minusNegativeNum);

使用a unary plus + 会将任何内容转换为数字。如果提供了一个数字,它将保持原样:

const str = "10.5";
const plusStr = +str;

console.log(plusStr);
console.log(typeof plusStr);


const negativeNum = -3;
const plusNegativeNum = +negativeNum;

console.log(plusNegativeNum);

上面也是表达式+-(rect.height / 1)的求值顺序。

那么,+-(rect.height / 1) 做了什么?与-rect.height 相同,但添加了两个无用的运算符。

应该注意,实际上不需要任何转换 - 不是因为一元减号已经完成,而是因为 the height property produces a number anyway:

const element = document.getElementById("myId")
const rect = element.getBoundingClientRect()

console.log(rect.height);
console.log(typeof rect.height);

const height = +-(rect.height / 1);
console.log(height);
#myId {
  width: 400px;
  height: 200px;
  background: red;
}
<div id="myId"></div>

所以整个表达式只是获取高度并反转其符号。

【讨论】:

  • 感谢您的详细解释和细分。然后我将在我的实现中使用-rect.height
【解决方案2】:

您能否提供找到此代码的链接? 但从你提供的情况来看,我同意你的看法。 + 运算符和除以一不会做任何事情。所以我会说这是一个错字,一些临时代码,或者开发人员喝了太多酒。

【讨论】:

  • 或者开发人员喝了太多酒”也许我们只是没有足够的酒来欣赏它。 :P
【解决方案3】:

我认为这是一个陷阱。我不确定,但如果你从文档中获取数字,你会得到字符串而不是数字。这个 + 在字符串中的数字之前(例如“10”)会将其转换为数字类型。

例如

"11" + 1 = "111" 

因为 javascript 将其连接为 2 个字符串。 但是

var a = "11"
+a makes it = 11

但遗憾的是,我认为restit脱离了上下文

编辑:

好吧。

  Math.floor(100 - (((rect.top >= 0 ? 0 : rect.top) / +-(rect.height / 1)) * 100)) < percentVisible

+-(rect.height / 1)) * 100

我认为这部分使这个数字成为百分比值。JS 不知道百分比。一切都是值 / 100,但要获得正确的值,你应该值 / 1。

【讨论】:

    猜你喜欢
    • 2018-02-19
    • 1970-01-01
    • 2010-10-10
    • 2010-10-25
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    • 1970-01-01
    相关资源
    最近更新 更多