JS中如何实现变量数值相加而非字符串拼接?
Hey there! Let's break down what's happening here and get you the correct sum you want.
The Root Issue: String Concatenation vs. Numeric Addition
In your current code, when you run this line:
document.write("The sum of x and y is " + x + y);
JavaScript is using the + operator for string concatenation (sticking text together) instead of adding the numbers. Here's the play-by-play:
- First, it combines the string
"The sum of x and y is "withx(3) to make the string"The sum of x and y is 3". - Then, it takes that new string and glues it to
y(2), resulting in"The sum of x and y is 32".
Quick Fix: Prioritize Numeric Addition
Wrap x + y in parentheses to tell JavaScript to calculate the numeric sum first, before combining it with the string:
function getx() { x = 3; } function gety() { y = 2; } getx(); gety(); document.write("The sum of x and y is " + (x + y));
This will first compute 3 + 2 = 5, then append that number to your text, giving you the correct output: The sum of x and y is 5.
Better Long-Term Practice: Ditch Global Variables
While the quick fix works, using un-declared global variables (like your x and y) can cause messy bugs as you write more code. A cleaner approach is to have your functions return values instead:
function getx() { return 3; // Return the value directly instead of setting a global variable } function gety() { return 2; } // Store the returned values in properly declared variables const x = getx(); const y = gety(); document.write("The sum of x and y is " + (x + y));
This makes your code more predictable and easier to debug as you keep learning JavaScript functions.
内容的提问来源于stack exchange,提问作者rock3rd

