Javascript 如何将数据存储到变量中。?
朋友们好,我可以将变量的结果存储到“c”中吗。如果是,那么为什么我不能进一步使用数据进行算术计算。Javascript 如何将数据存储到变量中。?,javascript,Javascript,朋友们好,我可以将变量的结果存储到“c”中吗。如果是,那么为什么我不能进一步使用数据进行算术计算。 我从if-else声明中得到了1790的答案 变量应位于等号的左侧。document.write不返回值,因此您应该在该行之前执行赋值 var a=1800, b=10; if (a == b) { document.write(a - b) = c; } else if (a > b) { document.write(a - b)
我从if-else声明中得到了1790的答案 变量应位于等号的左侧。document.write不返回值,因此您应该在该行之前执行赋值
var a=1800, b=10;
if (a == b) {
document.write(a - b) = c;
}
else if (a > b) {
document.write(a - b) = c;
}
else {
document.write("Everything is wrong.") = c;
}
var x = c * 100;
document.write(x);
首先,您应该初始化变量,否则if语句就没有任何意义,因为在if语句中,您所做的事情与使用
|
或运算符所做的事情相同
else if (a > b) {
c = a - b;
document.write(c);
}
这甚至不是有效的JavaScript 您正在调用一个函数(document.write()),然后对其使用赋值运算符(您不能这样做) 最终结果相当于编写类似
undefined=7
的代码,因为JavaScript将首先计算/执行函数
C也从来没有在任何地方声明过,所以您可能也会遇到这个问题
相反,您需要执行以下操作:
const a = 1800;
const b = 10;
let c = null;
if (a == b || a > b) {
c = (a - b) * 100;
} else {
c = "Everything is wrong.";
}
document.write(c);
Document.write不会返回公式的结果,并且您的作业不正确。分配变量时,请这样考虑: “我有一个变量C。我希望C存储Y的值。” 所以C=Y,这和数学做的方式是相反的。(方程式=结果。)在编程中,它往往是StorageLocation=方程式 为什么我说倾向于?一定有一种语言不符合这种模式 这是您的更新代码:
let c; //declare C but don't assign it a value
const a = 1800;
const b = 10;
if(a === b || a > b){ //Since you're doing the same thing combine the conditions
c = a - b;
document.write(c);
} else {
document.write("Somethings wrong")
}
let x = c * 100; // If c is undefined you'll get NaN similar to above, otherwise you'll get a result
document.write(x);
不清楚你想做什么。存储什么结果?
var c=a-b代码>?我不确定你想做什么,但是你的变量赋值是反向的,我做了什么。我想要的是存储在变量“a”和“b”中的更大的数字。所以我使用if-else语句进行筛选。这是我发布的简短代码。所以现在我得了a>b。然后用else if语句编写文档,写出(a-b)=c;我得到c作为答案并存储到变量c中。现在我想对x个结果进行var(c*10)。但我什么也得不到。对不起,英语不好。我正在尝试学习代码(在JS中非常新)哇,这就是我一直在寻找的。谢谢你的帮助。谢谢大家。
var a=1800, b=10, c = 0; // Initializing c for document.write is a good practice.
if (a == b) {
c = a-b;
}
else if (a > b) {
c = a-b; /* As the other two posters noticed ... this does the same thing as the a == b. I am assuming you'd like to do something a little different with the two blocks. */
}
else {
c = "Everything is wrong.";
}
document.write(c); // "Don't Repeat Yourself" or "DRY" is good practice.
var x = c * 100; // Note - Multiplying your string by 100 is weird.
document.write(x);