how to make jquery each a number

后端 未结 3 1123
南笙
南笙 2021-02-08 15:26

This is my code:

$.each(3, function(n) {
    alert(n);
});

I want to alert three times but it doesn\'t work. What can I do?

3条回答
  •  误落风尘
    2021-02-08 15:50

    Late answer, but another option would be to prototype the Number with a method that would call a callback that many times.

    Number.prototype.loop = function(cb) {
        for (var i = 0; i < this; i++) {
            cb.call(this, i);
        }
        return this + 0;
    };
    

    Then call it like this:

    (3).loop(i => alert(i))
    

    However, it should be noted it is considered bad practice to modify standard prototypes like this. See the section on this MDN page called Bad practice: Extension of native prototypes.

    RightJS does something like this. (Others probably too.)

提交回复
热议问题