javascript string.length 返回未定义?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9582141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
string.length returns undefined?
提问by Davor Zubak
function checkInputData() {
$('.mainSearchSubmit').live('click', function () {
var inputData = $(this).parent().children().eq(0).val();
console.log(inputData.length);
//this returns undefined
console.log(inputData);
//and this returns text from inpu so i know there is data
});
}
Any ideas why is this happening, in other cases when retrieving val() from input it always comes as string??
任何想法为什么会发生这种情况,在其他情况下,当从输入中检索 val() 时,它总是作为字符串出现?
回答by Hubro
The only explanation to length
being undefined is if inputData is not a string. You neglected to mention what type of input you're working with, but in any case, casting to string should solve the issue:
length
未定义的唯一解释是 inputData 不是字符串。您忽略了您正在使用的输入类型,但无论如何,转换为字符串应该可以解决问题:
function checkInputData() {
$('.mainSearchSubmit').live('click', function () {
var inputData = $(this).parent().children().eq(0).val();
inputData = String(inputData); // Cast to string
console.log(inputData.length);
//this returns undefined
console.log(inputData);
//and this returns text from inpu so i know there is data
});
}