本文介绍了在JavaScript中使用科学记数法的陷阱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题寻求开发者代码格式化意见。就个人而言,我更喜欢在我的JS代码中使用科学记数法,因为我相信它更具可读性。对我来说, 6e8 600000000 更具可读性。话虽这么说,我只是在寻找JS中用科学记数法指定数字的潜在风险和缺点。我不经常在野外看到它并且想知道是否有技术推理,或者仅仅是因为开发人员的druthers。

This question is not seeking developer code formatting opinions. Personally, I prefer to use scientific notation in my JS code when I can because I believe it is more readable. For me, 6e8 is more readable than 600000000. That being said, I am solely looking for potential risks and disadvantages specifying numbers in scientific notation in JS. I don't see it often in the wild and was wondering if there is technical reasoning for that or if it simply because of developer's druthers.

推荐答案

你没有看到科学记谱法经常在野外,因为在JS中实际输入的唯一数字往往是常量:

You don't see scientific notation "often in the wild" because the only numbers that actually get typed in JS tend to be constants:


  • 以代码为中心的常量(例如枚举和级别)往往很小。

  • 物理/数学常数(如π或e)倾向于非常具体。

这些都不会从科学记数法中获益太多。

Neither of these benefit from scientific notation too much.

我已经看到'在野外'as:

I have seen Plank's constant 'in the wild' as:

const h = 6.62607004e-34;
console.log('Plank', h);

其他通常有意义的地方是时间限制,例如一天中ms的数量为 864e5 。例如:

The other place it often makes sense is time limits, for instance the number of ms in a day as 864e5. For instance:

function addDaysToDate(date, days) {
  if (days === 0)
    return date;
  date.setTime(864e5 * days + date.valueOf());
  return date;
}

const now = new Date();
const thisTimeTomorrow = addDaysToDate(now, 1);
console.log('This time tomorrow', thisTimeTomorrow);

我认为没有任何技术理由不使用这种表示法,更多的是开发人员完全避免硬编码。

I don't think there's any technical reason not to use this notation, it's more that developers avoid hard coding numbers at all.

我认为没有任何风险。您可能必须小心字符串中的数字,但如果您这样做,则此语法比数字本地化(例如,输入的DE用户20.000,00的问题要小得多)。 ,期待 2e4 ,但得到 2e6 感谢不变数字格式交换千位和小数分隔符)。

I don't think there are any risks. You may have to be careful with numbers in strings, but if you're doing that then this syntax is a far smaller issue than, say, number localisation (for instance a DE user entering "20.000,00", expecting 2e4, but getting 2e6 thanks to invariant number formatting swapping the thousand and decimal separators).

我想补充一点,对于小数字,JS默认会输出该语法,但是避免大数到一点(由浏览器决定) :

I'd add that JS will output that syntax by default anyway for small numbers, but avoids for large numbers up to a point (which varies by browser):

console.log('Very small', 1234 / 100000000000)
console.log('Large, but still full in some browsers', 1e17 * 1234)
console.log('Large, scientific', 1e35 * 1234)

这篇关于在JavaScript中使用科学记数法的陷阱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 22:40