首页 > 解决方案 > 如何以 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 有什么错?

标签: javascripthtmlcssfunctionecmascript-6

解决方案


你得到这个是因为你在声明它之前使用了常量,相反,你的代码应该是这样的:

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);

};

推荐阅读