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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:07:06  来源:igfitidea点击:

string.length returns undefined?

javascriptjquerystringundefined

提问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 lengthbeing 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
    });
 }