简体   繁体   中英

What is the purpose of this operator "+=" in this context?

I am learning some basic JS and how its results are viewed on HTML. I come across this:

<!DOCTYPE html>
<html>
<body>
    <h1>Demo: JavaScript Arithmatic Operators</h1>
    <p>x = 5, y = 10, z;</p>
    <p id="p1">x+y=</p>
    <script>
        var x = 5, y = 10;
        var z = x + y
        document.getElementById("p1").innerHTML += z; 
    </script>
</body>
</html>

As far as I have read on the operator '+=', it adds the right operand to the left operand and then saves it back to the left operand. However, I am confused on what is the purpose of '+=' in this line?

document.getElementById("p1").innerHTML += z; 

// equals to
document.getElementById("p1").innerHTML = document.getElementById("p1").innerHTML + z; 

// in this case
document.getElementById("p1").innerHTML = "x+y=" + 15

// finally, you will see "x+y=15" on the page

It simply appends right operand value(15) to content of <p id="p1"> tag(thats x+y). So it results as "x+y=15"

For more clarification:

document.getElementById("p1").innerHTML += z; In this line, it takes the innerHTML(current content) of html element with id 'p1'(here its a <p> tag), append right operand(here its variable z: which contains value 15 after js add operation result) to that content, and set it back as that <p> tag's innerHTML.

if you have two variable do you want to add these two and store in one of them like

a=5; b=4;

a = a + b this is same as a += b; so in your case you can use

document.getElementById("p1").innerHTML = document.getElementById("p1").innerHTML + z; 

or 
document.getElementById("p1").innerHTML += z; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM