繁体   English   中英

如何以JSON格式输出数据?

[英]How to output data in format of 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);

};

您必须在JSON.stringify(celsiusObject)之上定义celsiusObject;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM