Here's a Python-like range() for JavaScript. Is it new?
- From: Jonathan Fine <jfine@xxxxxxxxx>
- Date: Thu, 26 Feb 2009 20:20:15 +0000
Hello
Here's a Python-like range function that might be useful. I've not tested it for performance, but expect it to be quicker on large ranges, and no slower for small ones.
If anyone has seen this trick before, please do tell the newsgroup. And the same goes for bugs.
For arrays one can, of course, use the trick directly.
for (i in myArray){
value = myArray[i];
// do something.
}
I've found that in Firefox/SpiderMonkey adding to Array.prototype breaks the trick.
===
$ cat js/range.js
// Definition of range.
var _range;
// FF2, FF3
_range = '.....................................................';
// IE6
_range = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
var range = function(n){
return _range.slice(0, n);
};
// Use of range.
var i;
var x = [];
for (i in range(11)){
x[i] = 10 - i;
};
print(x);
for (i in range(x.length)){
x[i] = i * i;
}
print(x);
$ js js/range.js
10,9,8,7,6,5,4,3,2,1,0
0,1,4,9,16,25,36,49,64,81,100
==
--
Jonathan
.
- Follow-Ups:
- Performance: for(i=0; i<n; i++) vs. for (i in object)
- From: Jonathan Fine
- Re: Here's a Python-like range() for JavaScript. Is it new?
- From: Robin
- 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: Thomas 'PointedEars' Lahn
- Performance: for(i=0; i<n; i++) vs. for (i in object)
- Prev by Date: Re: Scope problem?
- Next by Date: Re: Get index of same name input element
- Previous by thread: The most legitimate way of making money online with no investment and payment proof
- Next by thread: Re: Here's a Python-like range() for JavaScript. Is it new?
- Index(es):
Relevant Pages
|
Loading