javascript - 如何以 JSON 格式输出数据?
问题描述
我尝试以 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 有什么错?
解决方案
你得到这个是因为你在声明它之前使用了常量,相反,你的代码应该是这样的:
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);
};
推荐阅读
- ios - UISearchBar 过滤自定义 UITableViewCells
- r - 使用`read.csv`时如何防止分隔符成为输入的一部分?
- typescript - 如何调用方法来运行索引的所有实例
- mysql - Mysql docker 文件未运行:断言失败:log0recv.cc:3561:err == DB_SUCCESS 线程 139674864518912
- arrays - C - 动态分配 3 维数组的函数(使用 malloc)
- nuxt.js - Nuxt.js 中特定布局的自定义转换
- python - 将矩阵(或二维数组)存储为字典中每个键的值
- c - 在将变量声明为布尔类型和!之后,这段代码的含义是什么?
- excel - VBA Excel用公式改变文本框的功能
- ruby-on-rails - 如何在 Rails 中真正发送电子邮件