You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS中如何实现变量数值相加而非字符串拼接?

Why You're Getting "32" Instead of "5" & How to Fix It

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:

  1. First, it combines the string "The sum of x and y is " with x (3) to make the string "The sum of x and y is 3".
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:12:03