lundi 13 juin 2016

jQuery/JavaScript code explanation

I was looking for a way to convert form data to JavaScript object with jQuery and I came across this thread: Convert form data to JavaScript object with jQuery The most popular answer has this code in it:

$.fn.serializeObject = function() {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) { // ???
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
};

However there is a piece of code in it that I am not exactly sure of what is doing(I think is a mistake)

if (!o[this.name].push) {
   o[this.name] = [o[this.name]];
}

Objects do not have a property named push. There is a JS array method .push() which, besides pushing elements into the array, it returns the number of elements in the array, but in this case there are no braces let alone that, as you can see, o is an object. I tried this code with console.log but it never executes. Do any of you have any idea, what is the purpose of this if statement? This code is in other threads as well so I am not sure who the author of this code is.

Thank you in advance

Aucun commentaire:

Enregistrer un commentaire