我尝试以JSON格式输出结果。 但是出现错误“未定义celsiusObject”。
部分代码:
const select = document.getElementById('select');
switch (select.value) {
case 'celsius':
value1.value = Math.round(9/5 * (parseInt(currentValue.value)) + 32) + 'F';
value2.value = Math.round(parseInt(currentValue.value) + 273.15) + 'K';
json.value = JSON.stringify(celsiusObject);
const celsiusObject = {
F: Math.round(9/5 * (parseInt(currentValue.value)) + 32),
K: Math.round(parseInt(currentValue.value) + 273.15)
}
};
HTML:
<div id="application">
<input id="currentValue" type="number" placeholder="enter value of temperature">
<select id="select">
<option value="celsius">Celsius</option>
<option value="fahrenheit">Fahrenheit</option>
<option value="kelvin">Kelvin</option>
</select>
</br>
<button id="convert">Convert</button>
</br>
<input id="value1" type="text">
</br>
<input id="value2" type="text">
</br>
<input id="value3" type="text">
</div>
获取JSON错了什么?
答案 0 :(得分:4)
之所以会这样,是因为在声明常量之前使用了常量,相反,代码应如下所示:
const select = document.getElementById('select');
switch (select.value) {
case 'celsius':
value1.value = Math.round(9/5 * (parseInt(currentValue.value)) + 32) + 'F';
value2.value = Math.round(parseInt(currentValue.value) + 273.15) + 'K';
const celsiusObject = {
F: Math.round(9/5 * (parseInt(currentValue.value)) + 32),
K: Math.round(parseInt(currentValue.value) + 273.15)
}
json.value = JSON.stringify(celsiusObject);
};
答案 1 :(得分:-1)
您必须在JSON.stringify(celsiusObject)之上定义celsiusObject。