$R(start, end[, exclusive = false]) → ObjectRange
Creates a new ObjectRange
object. This method is a convenience wrapper around the ObjectRange
constructor, but $R
is the preferred alias.
ObjectRange
instances represent a range of consecutive values, be they numerical, textual, or of another type that semantically supports value ranges. See the type's documentation for further details, and to discover how your own objects can support value ranges.
The $R
function takes exactly the same arguments as the original constructor: the lower and upper bounds (value of the same, proper type), and whether the upper bound is exclusive or not. By default, the upper bound is inclusive.
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html>
- <head>
- <title>$R</title>
- <script type="text/javascript" language="javascript"
- src="prototype.js" ></script>
- <script>
- // 依次输出1,2,3,4,为true时,右括号为开区间
- function test_R1(){
- var range = $R(1, 5, true);
- range.each(function(value){
- alert(value);
- });
- }
- // 依次输出1,2,3,4,5,为false时,右括号为闭区间
- function test_R2(){
- var range = $R(1, 5, false);
- range.each(function(value){
- alert(value);
- });
- }
- function test(){
- alert($R(0, 10).include(10));
- // -> true
- alert($A($R(0, 5)).join(', '));
- // -> '0, 1, 2, 3, 4, 5'
- alert($A($R('aa', 'ah')).join(', '));
- // -> 'aa, ab, ac, ad, ae, af, ag, ah'
- alert($R(0, 10, true).include(10))
- // -> false
- var arr = $R(0, 10, true).each(function(value) {
- // invoked 10 times for value = 0 to 9
- })
- arr.each(function(value){
- alert(value);
- });
- }
- </script>
- </head>
- <body>
- <form>
- <input type="button" value="click (exclusive = true)"
- onclick="test_R1()" />
- <input type="button" value="click (exclusive = false)"
- onclick="test_R2()" />
- <input type="button" value="click" onclick="test()"/>
- </form>
- </body>
- </html>
以下是官方特别让注意的:
Warning
Be careful with String
ranges: as described in its String#succ
method, it does not use alphabetical boundaries, but goes all the way through the character table:
- $A($R('a', 'e'))
- // -> ['a', 'b', 'c', 'd', 'e'], no surprise there
- $A($R('ax', 'ba'))
- // -> Ouch! Humongous array, starting as ['ax', 'ay', 'az', 'a{', 'a|', 'a}', 'a~'...]
转载于:https://blog.51cto.com/sucre/410438