js for循环代码在调用前先打印出来
The js for-loop code is printed before it is called
我是一名新 Javascript 程序员,这是我的第一个问题。
我有以下代码:
- 从名为 celsius 的变量中获取每个值
- 将该值赋给名为 calculate 的函数并将其转换为
华氏温度。
- 华氏值取回第一个
函数然后打印到第一个函数
function calculate() {
var celsius = [12, 45, 99, -40];
for (i=0 ; i<celsius.length; i++) {
document.write("The value is " + celsius[i] + " and is equal to " + count(celsius[i]) + "<br>")
}
}
function count(num) {
var degfarhen = 9/5 * parseFloat(num) + 32;
degfarhen = degfarhen.toFixed(1);
document.write(degfarhen)
}
但这会发生
53.6The value is 12 and is equal to undefined
113.0The value is 45 and is equal to undefined
210.2The value is 99 and is equal to undefined
-40.0The value is -40 and is equal to undefined
华氏度的值打印在句子之前,实际上必须打印的位置未定义。
将document.write(degfarhen)
更改为return degfarhen;
在函数 count
中,您正在调用 document.write()
,它将立即写入文档。
因为这是在另一个document.write
内部调用的(在for循环中),所以内部的会先于外部的写入。您看到 "undefined" 是因为函数没有返回值。
你需要做的是 return degfarhen
在 count
的末尾而不是 document.write-ing 它..
function count(num) {
// calculation remains the same
return degfarhen;
}
我是一名新 Javascript 程序员,这是我的第一个问题。
我有以下代码:
- 从名为 celsius 的变量中获取每个值
- 将该值赋给名为 calculate 的函数并将其转换为 华氏温度。
- 华氏值取回第一个 函数然后打印到第一个函数
function calculate() {
var celsius = [12, 45, 99, -40];
for (i=0 ; i<celsius.length; i++) {
document.write("The value is " + celsius[i] + " and is equal to " + count(celsius[i]) + "<br>")
}
}
function count(num) {
var degfarhen = 9/5 * parseFloat(num) + 32;
degfarhen = degfarhen.toFixed(1);
document.write(degfarhen)
}
但这会发生
53.6The value is 12 and is equal to undefined
113.0The value is 45 and is equal to undefined
210.2The value is 99 and is equal to undefined
-40.0The value is -40 and is equal to undefined
华氏度的值打印在句子之前,实际上必须打印的位置未定义。
将document.write(degfarhen)
更改为return degfarhen;
在函数 count
中,您正在调用 document.write()
,它将立即写入文档。
因为这是在另一个document.write
内部调用的(在for循环中),所以内部的会先于外部的写入。您看到 "undefined" 是因为函数没有返回值。
你需要做的是 return degfarhen
在 count
的末尾而不是 document.write-ing 它..
function count(num) {
// calculation remains the same
return degfarhen;
}