gpt4 book ai didi

javascript - 未定义的计数作为变量——扰乱了我的 isObjEmpty() 函数

转载 作者:行者123 更新时间:2023-12-02 17:32:35 25 4
gpt4 key购买 nike

仅当对象不为空时,我才尝试发布对象。但是,我的代码会导致属性变得未定义 - 当这种情况发生时,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”,则用户名变量将变得未定义,因此在执行操作时不会发送该变量发布(我在服务器端控制台记录对象,并且不考虑 undefined variable ,这很好)。

  • 当变量的长度低于 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 );
});
});

关于javascript - 未定义的计数作为变量——扰乱了我的 isObjEmpty() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22925770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com