首页 > 解决方案 > Print value in more than one const statement

问题描述

Related script:

window.onload = function calcPreco() {
for(const cloud of Array.from(document.getElementsByName("cloud"))) {
    fetch("_config/buscar_valor.php?id="+cloud.getAttribute("cloudid")+"&periodicidade=monthly")
     .then(res => res.text())
     .then(preco => {
        preco -= cloud.getAttribute("desconto");
        const valor = cloud.querySelector(".mostrar_valor").innerText = preco.toFixed(2).replace('.', ',');
     })
    }
}

I need it to print to another <span> with another class, but before doing the subtraction.

I tried something like that, but it did not work:

.then(preco => {
        const valor = cloud.querySelector(".NEW_CLASS").innerText = preco.toFixed(2).replace('.', ',');
        preco -= cloud.getAttribute("desconto");
        const valor = cloud.querySelector(".mostrar_valor").innerText = preco.toFixed(2).replace('.', ',');
     })

That is, it must first print the original value, and then the value with the subtraction done.

How to use two const statements in this case?

标签: javascriptjqueryajax

解决方案


使用 var 或 const 时,将其视为分配内存位置。当您在同一范围内分配 2 个内存位置时,它不知道该怎么做。因此,请使用不同的名称或从变量声明中删除 var/const。一个好的做法是定义然后使用:

var someVariable;
if(condition){
   someVariable = 'some answer';
}
else
{
   someVariable = "some other answer';
}

或连接:

var someVariable;
someVariable = "some"; // mostly this and the line above will be one line.
someVariable += " answer";

另外,如果您这样做:

valor = "some html";
valor = "some other html"; // This will overwrite the first answer.

也很好读:

https://airbrake.io/blog/javascript-error-handling/redeclaration-formal-parameter-x

可能您正在寻找的内容:

var valor = cloud.querySelector(".NEW_CLASS").innerText = preco.toFixed(2).replace('.', ',');
preco -= cloud.getAttribute("desconto");
valor += cloud.querySelector(".mostrar_valor").innerText = preco.toFixed(2).replace('.', ',');

推荐阅读