未定义的计数为变量 - 弄乱了我的isObjEmpty()函数

Undefined counting as a variable -- messes up with my isObjEmpty() function

本文关键字:我的 乱了 isObjEmpty 函数 变量 未定义      更新时间:2023-09-26

我试图仅在对象不为空时才post对象。但是,我有导致属性变得未定义的代码 - 当发生这种情况时,obj 不再为空,post仍然会发生。

userSearchData = {};
$('#addContactForm').keyup(function()
{
    var email = $(this).find('input[name="email"]').val();
    var username = $(this).find('input[name="username"]').val();
    var fullName = $(this).find('input[name="fullName"]').val();
    userSearchData.email = email.length >= 3 ? email : undefined;
    userSearchData.username = username.length >= 3 ? username : undefined;
    userSearchData.fullName = fullName.length >= 3 ? fullName : undefined;
    console.log(userSearchData);
    if ( !isEmpty(userSearchData) )
    {
        console.log("Is empty")
        $.post( '/post/addContact', { userSearchData: userSearchData }, function( data ) 
        {
            console.log( data );
        });
    }
});

这是一个"搜索"表单,因此,如果用户键入例如"Blabla"作为用户名,然后删除字母使其成为"Bl",那么用户名变量将变得未定义,因此在发布帖子时不会发送它(我在服务器端控制台记录对象,并且不考虑未定义的变量哪个是好的)。

  • 如何使变量完全删除,而不是在变量长度低于 3 时未定义?

  • 如果所有键都未定义,我可能会修改 isEmpty 函数以返回 false,这样做会更好吗?如果是这样,你会怎么做?

    var hasOwnProperty = Object.prototype.hasOwnProperty;
    function isEmpty (obj)
    {
        // null and undefined are "empty"
        if (obj == null) return true;
        // Assume if it has a length property with a non-zero value
        // that that property is correct.
        if (obj.length > 0)    return false;
        if (obj.length === 0)  return true;
        // Otherwise, does it have any properties of its own?
        // Note that this doesn't handle
        // toString and valueOf enumeration bugs in IE < 9
        for (var key in obj) {
            if (hasOwnProperty.call(obj, key)) return false;
        }
        return true;
    }
    

整个事情似乎毫无意义,你可以这样做

$('#addContactForm').on('keyup', function() {
    var userSearchData = {}, self = this;
    $.each(['email', 'username', 'fullName'], function(_, el)  {
        var val = $(self).find('input[name="'+el+'"]').val();
        if ( val.length > 3 ) userSearchData[el] = val;
    });
    $.post( '/post/addContact', { userSearchData: userSearchData }, function( data ) {
        console.log( data );
    });
});

仅在满足条件时将属性添加到对象。

if ( username.length >=3 ) {
    userSearchData.username = username;
}
if ( username in userSearchData ) {
    // do stuff
}
你可以在

JS中delete属性,但更好的解决方法是确保你的代码在应该发布的时候发布。

if (obj === null || obj === undefined) return;

或者在这里可能会有所帮助。

此外,for(key in obj)是旧式的"迭代原型",并且非常不鼓励,所以你可能想要这个:

var keys = Object.keys(obj);
if(keys.length === 0) ...
keys.forEach(function(key) { ... });

你的意思是你想这样做吗?

if(!isEmpty(userSearchData)){
     $.post( '/post/addContact', { userSearchData: userSearchData }, function( data ) 
    {
        console.log( data );
    });
}