gpt4 book ai didi

javascript - Javascript 如何处理 BODMAS?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:32:46 25 4
gpt4 key购买 nike

我一直在为我目前正在从事的项目使用 Javascript 做一些数学运算,并且偶然发现了以下内容:

我正在计算结果列表中剩余的结果数量(有一个“加载更多”按钮)

代码如下:

if (data.length > startIndex + maxLoadAmount) {
var loadMoreButton = new LoadButton()
loadButton.ToLoad = data.length - startIndex + maxLoadAmount;

loadMoreButton.click(function () {
var amountOfCurrentWidgets = $(this).parent().children('.widget').length;
this.remove();
loadChildren(amountOfCurrentWidgets, selector, data, widgetType);
});
$(selector).append(loadMoreButton);
}

当我运行它时,我对结果感到惊讶!

在特定测试中,有 16 个可用小部件,当从索引 0 开始最多显示 5 个时,结果为 21。

我将其追踪到 javascript 在加法之前执行减法。您可以在此处的 jsfiddle 中重现它: http://jsfiddle.net/JamesPattison/3hvr4vsr/

解决方法是将添加内容括在方括号中,但我想我真正要问的是:

我要疯了吗?

最佳答案

在 JavaScript 中加减法 have the same precedence并且两者都具有从左到右的结合性。因此,使用 fiddle 中的代码:

var x = 16, y = 0, z = 5;
var result = x-y+z; //16-0+5, expected by BODMAS: 16-(0+5) = 11
$('#results').html(result.toString())

result 是这样计算的:

(16 - 0) + 5

这就是它在 JavaScript、Java、C、C++、C# 和我能想到的所有其他语言中的计算方式。

如果加法有一个比减法更高的优先级,它会以不同的方式分解,就像乘法一样:

16 - 0 * 5 => 16 - (0 * 5)

但事实并非如此。


Re BODMAS,确实应该这样写:

BODMAS

来自 the WikiPedia article on order of operations :

These mnemonics may be misleading when written this way, especially if the user is not aware that multiplication and division are of equal precedence, as are addition and subtraction.

类似地,以下所有引用资料都说在标准算术中,除法和乘法具有相同的优先级,加法和减法具有相同的优先级:

The Order of Operations: PEMDAS - purplemath.com :

A common technique for remembering the order of operations is the abbreviation "PEMDAS", which is turned into the phrase "Please Excuse My Dear Aunt Sally". It stands for "Parentheses, Exponents, Multiplication and Division, and Addition and Subtraction". This tells you the ranks of the operations: Parentheses outrank exponents, which outrank multiplication and division (but multiplication and division are at the same rank), and these two outrank addition and subtraction (which are together on the bottom rank)

Math Steps - eduplace.com :

The rules are:

  1. Multiply and divide from left to right.
  2. Add and subtract from left to right.

Rules of arithmetic - mathcentre.ac.uk :

This is hard to remember so here’s an acronym to help you — BODMAS. It means:

enter image description here

where division and multiplication have the same priority, and also addition and subtraction have the same priority, so in each case we have bracketed them together.

关于javascript - Javascript 如何处理 BODMAS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30346249/

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