简体   繁体   English

数组null无法在JavaScript中进行验证

[英]Array null not validating in javascript

In my javascript i am trying to check an array if empty.If there is no item in <li> then array will be empty and this should throw error but it is not working. 在我的JavaScript中,我正在尝试检查数组是否为空。如果<li>没有项目,则数组将为空,这应该引发错误,但它不起作用。 Here is my code 这是我的代码

 var phrases = [];
        $('#listDiv #hiddenItemList').each(function () {
            var phrase = '';
            $(this).find('li').each(function () {
                var current = $(this);
                phrase += $(this).text() + ";";
            });
            phrases.push(phrase);
        });

        if (phrases === undefined || phrases.length == 0 )
        {
            $.alert("Please select rate type, high rate and low rate", {
                title: "Rates Info",
                type: "danger"
            });
            return false;
        }

You have to check that you're not just pushing an empty string into the array. 您必须检查您是否只是将空字符串推入数组。 This will make the array phrases have length and not be undefined but won't be what you're looking for. 这将使数组短语具有长度并且不会被定义,但是不会是您要的内容。

    var phrases = [];
            $('#listDiv #hiddenItemList').each(function () {
                var phrase = '';
                $(this).find('li').each(function () {
                    var current = $(this);
                    phrase += $(this).text() + ";";
                });
                if ( phrase != '' ) {
                  phrases.push(phrase);
                }
            });

            if (phrases === undefined || phrases.length == 0 )
            {
                $.alert("Please select rate type, high rate and low rate", {
                    title: "Rates Info",
                    type: "danger"
                });
                return false;
            }

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

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