Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Array.prototype.each (https://javascript.ru/forum/misc/43064-array-prototype-each.html)

Manyahin 20.11.2013 14:40

Array.prototype.each
 
['test',false,12].each( function() {
  alert(this);
})


Задание, написать функцию each.
Начинаю писать,

Array.prototype.each = function(fn) {
  for(var el in this) {
    fn(this[el]);
  }
}


Выводит 4 раза [Object Window]. Подскажите, в чем проблема?

Manyahin 20.11.2013 14:47

Ок, забыл вызвать call.
Array.prototype.each = function(fn) {
  for(var el in this) {
    fn.call(this[el]);
  }
}


А как быть с тем, что четвертым елементом он выкидывает функцию each?

рони 20.11.2013 14:52

Manyahin,
:-?
Array.prototype.each = function(fn) {
  for(var i in this) {
   this[i] = fn(this[i]);
  }
  return this
}

alert([1,2,3].each(function (a)
{
   return a*a
}));

Manyahin 20.11.2013 14:55

Ок, это норм?
Array.prototype.each = function(fn) {
  for(var el in this) {
    if(Array.prototype.each != this[el])
      fn.call(this[el]);
  }
}

рони 20.11.2013 15:14

Manyahin,
:write:
Array.prototype.each = function(fn) {
    for (var i=0; i<this.length; i++)  {this[i] = fn.call(this, this[i], i);}
    return this
}

alert([1,2,3].each(function (a)
{
   return a*a
}));

['test',false,12].each( function(el, i) {
  alert([el,i]);
  return el
})


Часовой пояс GMT +3, время: 04:50.