我正在调试一些 javascript,并不断遇到 javascript [object]
(例如,当我显示带有值的警报时,它显示为 [object]
或 NaN
)。我正在尝试读取该对象的内容。我知道在 Java 中,这对于 deepToString();
来说是一个完美的工作。是否有与该方法等效的 javascript?
这是生成上述对象的代码...
e = document.getElementById("contServer"); // contServer is an integer variable
var valueCS = parseInt(e.options[e.selectedIndex].value);
//Value CS is a four-byte variable calculated from e
有没有关于“解码”这个对象变量的 javascript 方法的想法,这样我就可以看到实际上里面是什么?
谢谢
最佳答案
在使用 select
元素时似乎有些困惑。
确保你有正确的标记:
<select id="contServer">
<option value="0">Zero</option>
<option value="10">Ten</option>
<option value="100" selected>Hundred</option>
<option value="1000">Thousand</option>
</select>
我们将值存储在 option
元素的 value
属性中。如果该属性不存在,则 value
将是位于开始 option
标签和结束 option
标签的文本。
接下来,像上面那样的“整数”值实际上并不是整数——它们是字符串。因此,在将它们用于任何数学运算之前,必须对其进行解析。在下面的简短演练中,我解释了获取所选值并将其解析为整数的过程。请仔细阅读它,我认为它会消除很多困惑:
// We now have a reference to the select object (with all of its object members)
var cServer = document.getElementById("contServer");
// Now we have a reference to all of the options within the select object
var options = cServer.options;
// Now a reference to the selected option
var selected = options[ cServer.selectedIndex ];
// And now the value of the selected option
var selValue = selected.value;
// Let's get the type of this value
var selType = typeof selValue;
// Convert this String to an Integer
var iSelType = parseInt( selType, 10 );
// We can also get the value from the select object itself
var cServerVal = cServer.value;
// But we would still need to parse it to an integer
var iCServerVal = parseInt( cServerVal, 10 );
我相信您对 NaN
的问题是由于试图解析一个非数值。例如,我们要尝试将一个单词解析为一个整数:
parseInt( "Hundred" );
结果将为 NaN
。这很可能发生在你身上。确保将数字存储在 option
标记之间,或存储在每个 option
标记的 value
属性内。
关于javascript - 是否有与 Java 的 deepToString() 等效的 JavaScript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10642582/