简体   繁体   中英

javascript prototype loop for in array

I am working on a project, which use a lot of "javascript". I have lot of "ajax" calls, which returns always à "json" array. For usefull reasons, I created two prototypes of Array object ("in_array" function and "shuffle" function).

Since I did the prototypes, all my "for in" loops are broken (two times showing "undefined" ...) I looked into google and stackoverflow, and I know my mistake now. Of course, if I delete my prototypes, the "undefined" go away.

But, I don't find all my answers.

First, I see lot of times, that using "for in" loops are bad, why ?

I develop in "PHP" or "python" too, and I DO love "for in" or "foreach" loops.

Secondly, I got a really lot of "for in" loops, so honnestly I prefer changing my prototypes, than changing my loops. Is this that much dirty to switch my prototypes to normal functions, and keep "for in" loops ?

Thirdly, I read that JQuery can correct this bug. My project did got JQuery, what is solution talking about (I only read that JQuery can correct this, not how).

Thank you,

EDIT : My prototypes code :

// FONCTIONS ARRAY
Array.prototype.shuffle = function () {
for (var i = this.length - 1; i > 0; i--) {
    var j = Math.floor(Math.random() * (i + 1));
    var tmp = this[i];
    this[i] = this[j];
    this[j] = tmp;
}

return this;
}

Array.prototype.in_array = function (needle) {
    for(var i = 0; i < this.length; i++) {
       if(this[i] == needle)
           return true;
    }
    return false;
}

Here is what a map function could look like. I wrote this out of the top of my head so there may be bugs.

function object_map(object, callback) {
    var key, ret = {};
    for (key in object) {
        if (Object.prototype.hasOwnProperty.call(object, key)) {
            ret[key] = callback(key, object[key]);
        }
    }
    return ret;
}

Your problem occurs:

  1. because you're adding (enumerable) functions to Array.prototype which will then appear any time you enumerate any array.

  2. because you shouldn't use for ... in to enumerate arrays, only for enumerating object keys.

If you know you're running on ES5 browsers, you can safely add functions to Array.prototype using Object.defineProperty :

Object.defineProperty(Array.prototype, 'shuffle', {
    value: function() {
        ...
    }
});

which defaults to creating non-enumerable properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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