如何捕捉JavaScript中的“未定义”?
问题描述:
我正在努力通过表单中的所有值,但我一直未定义,然后我的值显示出来。我正在动态创建表单,所以我认为未定义可能来自空白字段。如何捕捉JavaScript中的“未定义”?
下面是我用得到的所有元素的代码:
//try to get all elements
var output;
$(this).parents('form') // For each element, pick the ancestor that's a form tag.
.find(':input') // Find all the input elements under those.
.each(function(i) {
//alert(this.value+ " = " + i);
if (typeof this.value === "undefined") {
output = "nothing here";
} else {
output += this.value;
}
});
$("div#total").append("value = " + output + "<br>");
如果我进入1,2,3,4,5,6那么我的输出是:
hello value = undefined
value = undefined1
value = undefined1
value = undefined12
value = undefined12
value = undefined123
value = undefined123
value = undefined1234
value = undefined1234
value = undefined12345
value = undefined12345
value = undefined123456
结果是我想要的,除了未定义的部分。我看到了这个答案:JavaScript: undefined !== undefined?并试图提供他们的建议,但我似乎无法让我的程序保存值,如果值不是未定义的。
如果它帮助这里是全码:http://jsfiddle.net/lostsoul/rKLrZ/
答
初始化output
为空字符串。
var output = "";
如果input
没有价值,它会给你一个空字符串,而不是undefined
。
答
未初始化变量output
实际上具有值undefined
。
var output; // Value of output is undefined output += "2"; // undefined + "2" -> "undefined2"
+1你已经确定了两个问题。 – jfriend00 2012-07-13 03:55:06