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]. Подскажите, в чем проблема? |
Ок, забыл вызвать call.
Array.prototype.each = function(fn) {
for(var el in this) {
fn.call(this[el]);
}
}
А как быть с тем, что четвертым елементом он выкидывает функцию each? |
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
}));
|
Ок, это норм?
Array.prototype.each = function(fn) {
for(var el in this) {
if(Array.prototype.each != this[el])
fn.call(this[el]);
}
}
|
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, время: 05:43. |