使 javascript 代码更高效,避免创建更多行

Make javascript code more efficient avoid creating more lines

我在 JS 中有这个...有什么更好的代码效率?

var hello = parseInt(document.getElementById("hello").value);
var hello2 = hello * 0.02;
var hello1 = parseFloat(hello2);
var hello3 = Math.round(hello1 * 100) / 100;
if (hello3 > 3.11) {
  hello3 = 2.11;
}

Make javascript code more efficient

我能想到的唯一一件事就是您要求提高效率,那就是用更少的变量实现同样的目标。

此代码仅使用一个,hello3:

var hello3 = Math.round(parseFloat(parseInt(document.getElementById("hello").value)*0.02)*100)/100;

if (hello3 > 3.11) {
  hello3 = 2.11;
}

avoid creating more lines

我不确定你的意思是什么。理论上一切都可以在一行上,代码仍然有效:

var hello3 = Math.round(parseFloat(parseInt(document.getElementById("hello").value)*0.02)*100)/100; if (hello3 > 3.11) {hello3 = 2.11;}

但我看不出这样做有什么意义。

var hello1= parseFloat(hello2); 不是必需的,因为 hello2 已经是一个浮点数。

不清楚在计算结束时您需要哪些变量,但假设它只是 hello3 那么:

hello3 = ( ( ( hello3 = Math.round( parseInt(document.getElementById("hello").value) * 0.02 ) / 100 ) > 3.11 ) ? 2.11 : hello3 )

这真的很难读,所以我会这样格式化:

hello3 = (
    ( ( hello3 = Math.round( parseInt(document.getElementById("hello").value) * 0.02 ) / 100 ) > 3.11 )
        ?
    2.11
        :
    hello3
)

您可以将所有内容保存在一个变量中(不破坏缩进)。 我认为您不需要所有这些变量初始化,但在一行中对我来说太多了。

var hello1 = parseFloat(document.getElementById("hello").value) * 0.02;
hello1 = Math.round(hello1 * 100) / 100;
if (hello1 > 3.11) {
  hello1 = 2.11;
}

一个工作示例:https://stackblitz.com/edit/js-code-efficiency?file=index.js