Re: Here's a Python-like range() for JavaScript. Is it new?
- From: kangax <kangax@xxxxxxxxx>
- Date: Fri, 27 Feb 2009 15:29:46 -0500
Jonathan Fine wrote:
kangax wrote:
It seems unnecessary to create an array of N length just to perform certain action N times : )
Why not make a helper to perform a plain loop for you:
I think it easier to slice an array than to code a function. And the
That depends on what you mean by "easier".
performance will be better. I prefer to write data than write functions. But that's another topic.
Which performance?
Allocating memory for an array object of arbitrary length and then keeping that array in memory just to use its `length` is silly, don't
you think? AFAIK, similar concerns were the reasons iterators were implemented in newer versions of JavaScript.
function iterate(n, iterator, context) {
for (var i=0; i<n; i++) {
iterator.call(context, i);
}
}
and then:
iterate(10, function(i){
// ...
});
So here's a use case:
for (i=0; i < 10; i++){
this.update(i);
}
And using iterate:
iterate(10, function(i){
this.update(i);
});
But these are not the same, because 'this' has changed. So you need to
Yes, `this` references global object, since `call` was invoked with first argument being `undefined`.
use your additional parameter, to write:
iterate(10, function(i){
this.update(i);
}, this);
That's exactly why 3rd argument is there - to have more control over iterator context. You can also use some kind of `bind` implementation.
Well, I'd rather write
var that = this;
iterate(10, function(i){
that.update(i);
});
Sure, that's up to you.
--
kangax
.
- References:
- Here's a Python-like range() for JavaScript. Is it new?
- From: Jonathan Fine
- Re: Here's a Python-like range() for JavaScript. Is it new?
- From: Timo Reitz
- Re: Here's a Python-like range() for JavaScript. Is it new?
- From: Jonathan Fine
- Re: Here's a Python-like range() for JavaScript. Is it new?
- From: kangax
- Re: Here's a Python-like range() for JavaScript. Is it new?
- From: Jonathan Fine
- Here's a Python-like range() for JavaScript. Is it new?
- Prev by Date: Re: Need to speed up operations on array-like objects
- Next by Date: Re: Here's a Python-like range() for JavaScript. Is it new?
- Previous by thread: Re: Here's a Python-like range() for JavaScript. Is it new?
- Next by thread: Re: Here's a Python-like range() for JavaScript. Is it new?
- Index(es):
Relevant Pages
|