李伊娜 JavaScript 这样的方法 "range//", 在提供的边界范围内生成范围?

在 PHP 年你可以做到...


range/1, 3/; // Array/1, 2, 3/
range/"A", "C"/; // Array/"A", "B", "C"/


也就是说,有一个函数允许您获得数字或符号范围,传输上限和下边界。

有什么内置的 JavaScript 最初为此? 如果没有,我将如何实施它?
已邀请:

二哥

赞同来自:

数字


[...Array/5/.keys//];
=> [0, 1, 2, 3, 4]


迭代性质


String.fromCharCode/...[...Array/'D'.charCodeAt/0/ - 'A'.charCodeAt/0/ + 1/.keys//].map/i => i + 'A'.charCodeAt/0///;
=> "ABCD"


迭代


for /const x of Array/5/.keys/// {
console.log/x, String.fromCharCode/'A'.charCodeAt/0/ + x//;
}
=> 0,"A" 1,"B" 2,"C" 3,"D" 4,"E"


作为职能


function range/size, startAt = 0/ {
return [...Array/size/.keys//].map/i => i + startAt/;
}

function characterRange/startChar, endChar/ {
return String.fromCharCode/...range/endChar.charCodeAt/0/ -
startChar.charCodeAt/0/, startChar.charCodeAt/0///
}


作为键入的功能


function range/size:number, startAt:number = 0/:ReadonlyArray<number> {
return [...Array/size/.keys//].map/i =&gt; i + startAt/;
}

function characterRange/startChar:string, endChar:string/:ReadonlyArray<string> {
return String.fromCharCode/...range/endChar.charCodeAt/0/ -
startChar.charCodeAt/0/, startChar.charCodeAt/0///
}


lodash.js
https://lodash.com/docs/4.16.4#range
功能


_.range/10/;
=&gt; [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
_.range/1, 11/;
=&gt; [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
_.range/0, 30, 5/;
=&gt; [0, 5, 10, 15, 20, 25]
_.range/0, -10, -1/;
=&gt; [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
String.fromCharCode/..._.range/'A'.charCodeAt/0/, 'D'.charCodeAt/0/ + 1//;
=&gt; "ABCD"


老废话 es6 没有图书馆的浏览器:


Array.apply/null, Array/5//.map/function /_, i/ {return i;}/;
=&gt; [0, 1, 2, 3, 4]



console.log/[...Array/5/.keys//]/;



谢。

/ES6 信用尼罗河彼得森和其他评论

/
</string></number>

裸奔

赞同来自:

对于您可以使用的数字 ES6
Array.from//

,
https://developer.mozilla.org/ ... ility
, 除了 IE:

删节版:


Array.from/{length: 20}, /x,i/ => i/;


长版本:


Array.from/new Array/20/, /x,i/ => i/


从中创建一个数组 0 到 19 包括的。 这可以进一步减少到以下形式之一:


Array.from/Array/20/.keys///
// or
[...Array/20/.keys//]


您还可以指定较低和上限,例如:


Array.from/new Array/20/, /x,i/ => i + *lowerBound*/


这些文章更详细地描述了这一点:
http://www.2ality.com/2014/05/ ... .html

涵秋

赞同来自:

我最喜欢的形式 /

ES2015

/


Array/10/.fill/1/.map//x, y/ => x + y/


如果您需要参数的函数
step

:


const range = /start, stop, step = 1/ =>
Array/Math.ceil//stop - start/ / step//.fill/start/.map//x, y/ => x + y * step/

小姐请别说爱

赞同来自:

这是我的 2 美分:


function range/start, count/ {
return Array.apply/0, Array/count//
.map//element, index/ => index + start/;
}

二哥

赞同来自:

它适用于字符和数字,使用额外的步骤向前移动或返回。


var range = function/start, end, step/ {
var range = [];
var typeofStart = typeof start;
var typeofEnd = typeof end;

if /step === 0/ {
throw TypeError/"Step cannot be zero."/;
}

if /typeofStart == "undefined" || typeofEnd == "undefined"/ {
throw TypeError/"Must pass start and end arguments."/;
} else if /typeofStart != typeofEnd/ {
throw TypeError/"Start and end arguments must be of same type."/;
}

typeof step == "undefined" && /step = 1/;

if /end < start/ {
step = -step;
}

if /typeofStart == "number"/ {

while /step > 0 ? end >= start : end <= start/ {
range.push/start/;
start += step;
}

} else if /typeofStart == "string"/ {

if /start.length != 1 || end.length != 1/ {
throw TypeError/"Only strings with one character are supported."/;
}

start = start.charCodeAt/0/;
end = end.charCodeAt/0/;

while /step > 0 ? end >= start : end <= start/ {
range.push/String.fromCharCode/start//;
start += step;
}

} else {
throw TypeError/"Only string and number types are supported"/;
}

return range;

}


http://jsfiddle.net/ZaZAZ/
.

如果要增加自己的类型,请分配它
Array.range

.


var range = function/start, end, step/ {
var range = [];
var typeofStart = typeof start;
var typeofEnd = typeof end;

if /step === 0/ {
throw TypeError/"Step cannot be zero."/;
}

if /typeofStart == "undefined" || typeofEnd == "undefined"/ {
throw TypeError/"Must pass start and end arguments."/;
} else if /typeofStart != typeofEnd/ {
throw TypeError/"Start and end arguments must be of same type."/;
}

typeof step == "undefined" && /step = 1/;

if /end < start/ {
step = -step;
}

if /typeofStart == "number"/ {

while /step > 0 ? end >= start : end <= start/ {
range.push/start/;
start += step;
}

} else if /typeofStart == "string"/ {

if /start.length != 1 || end.length != 1/ {
throw TypeError/"Only strings with one character are supported."/;
}

start = start.charCodeAt/0/;
end = end.charCodeAt/0/;

while /step > 0 ? end >= start : end <= start/ {
range.push/String.fromCharCode/start//;
start += step;
}

} else {
throw TypeError/"Only string and number types are supported"/;
}

return range;

}

console.log/range/"A", "Z", 1//;
console.log/range/"Z", "A", 1//;
console.log/range/"A", "Z", 3//;


console.log/range/0, 25, 1//;

console.log/range/0, 25, 5//;
console.log/range/20, 5, 5//;

冰洋

赞同来自:

简单范围功能:


function range/start, stop, step/ {
var a = [start], b = start;
while /b < stop/ {
a.push/b += step || 1/;
}
return a;
}

莫问

赞同来自:

Array.range= function/a, b, step/{
var A= [];
if/typeof a== 'number'/{
A[0]= a;
step= step || 1;
while/a+step<= b/{
A[A.length]= a+= step;
}
}
else{
var s= 'abcdefghijklmnopqrstuvwxyz';
if/a=== a.toUpperCase///{
b=b.toUpperCase//;
s= s.toUpperCase//;
}
s= s.substring/s.indexOf/a/, s.indexOf/b/+ 1/;
A= s.split/''/;
}
return A;
}


Array.range/0,10/;
// [0,1,2,3,4,5,6,7,8,9,10]

Array.range/-100,100,20/;
// [-100,-80,-60,-40,-20,0,20,40,60,80,100]

Array.range/'A','F'/;
// ['A','B','C','D','E','F'/

Array.range/'m','r'/;
// ['m','n','o','p','q','r']

小姐请别说爱

赞同来自:

OK,

在 JavaScript 我们没有功能
range//

, 作为

PHP

, 因此,我们需要创建一个是一个相当简单的函数,我为您编写了一对单行功能并将它们分开

数字



字母表

, 如下所示:

对于数字 :


function numberRange /start, end/ {
return new Array/end - start/.fill//.map//d, i/ => i + start/;
}


让我们这样称呼它:


numberRange/5, 10/; //[5, 6, 7, 8, 9]


为了

字母表

:


function alphabetRange /start, end/ {
return new Array/end.charCodeAt/0/ - start.charCodeAt/0//.fill//.map//d, i/ => String.fromCharCode/i + start.charCodeAt/0///;
}


让我们这样称呼它:


alphabetRange/'c', 'h'/; //["c", "d", "e", "f", "g"]

奔跑吧少年

赞同来自:

舒服的

函数制作诀窍,在下面运行代码片段


function range/start, end, step, offset/ {

var len = /Math.abs/end - start/ + //offset || 0/ * 2// / /step || 1/ + 1;
var direction = start < end ? 1 : -1;
var startingPoint = start - /direction * /offset || 0//;
var stepSize = direction * /step || 1/;

return Array/len/.fill/0/.map/function/_, index/ {
return startingPoint + /stepSize * index/;
}/;

}

console.log/'range/1, 5/=> ' + range/1, 5//;
console.log/'range/5, 1/=> ' + range/5, 1//;
console.log/'range/5, 5/=> ' + range/5, 5//;
console.log/'range/-5, 5/=> ' + range/-5, 5//;
console.log/'range/-10, 5, 5/=> ' + range/-10, 5, 5//;
console.log/'range/1, 5, 1, 2/=> ' + range/1, 5, 1, 2//;



以下是如何使用它

范围 /开始,结束,步骤= 1,offset = 0

/;

包容性
range/5,10/ // [5, 6, 7, 8, 9, 10]


包容性
range/10,5/ // [10, 9, 8, 7, 6, 5]


退后
range/10,2,2/ // [10, 8, 6, 4, 2]


独家未来
range/5,10,0,-1/ // [6, 7, 8, 9] not 5,10 themselves


膨胀 - 扩展
range/5,10,0,1/ // [4, 5, 6, 7, 8, 9, 10, 11]


偏见 - Shochesale.
range/5,10,0,-2/ // [7, 8]


逐步扩展
range/10,0,2,2/ // [12, 10, 8, 6, 4, 2, 0, -2]


希望对你有帮助。

这就是它的工作原理。

基本上,我首先计算生成的阵列的长度,并为此长度创建零填充的阵列,然后用必要的值填充它


/step || 1/

=> 和其他类似的手段使用该值
step

, 如果没有授予,则使用
1


我们首先计算使用的阵列的长度
/Math.abs/end - start/ + //offset || 0/ * 2// / /step || 1/ + 1/

, 简化它 /difference* 两者都偏移 direction/step/

接收到长度后,我们使用初始化值创建一个空数组
new Array/length/.fill/0/;


现在我们有一个数组
[0,0,0,..]

到长度的长度。 我们将其进行比较并将新数组与我们需要的值返回
Array.map/function// {}/



var direction = start < end ? 1 : 0;

显然,如果
start

不小于
end

, 我们需要搬回。 我的意思是过渡到 0 到 5 或相反亦然

在每次迭代时
startingPoint

+
stepSize

*
index

将为我们提供我们需要的价值

涵秋

赞同来自:

var range = /l,r/ => new Array/r - l/.fill//.map//_,k/ => k + l/;

石油百科

赞同来自:

使用生成器的另一个版本 ES6 / 厘米。

/:


const RANGE = /a,b/ => Array.from//function*/x,y/{
while /x <= y/ yield x++;
}//a,b//;

console.log/RANGE/3,7//; // [ 3, 4, 5, 6, 7 ]


或者,如果我们只需要一项研究,那么:


const RANGE_ITER = /a,b/ => /function*/x,y/{
while /x++< y/ yield x;
}//a,b/;

for /let n of RANGE_ITER/3,7//{
console.log/n/;
}

郭文康

赞同来自:

使用
https://developer.mozilla.org/ ... rator
和射击功能:


var range = /start, end/ => [...Array/end - start + 1/].map//_, i/ => start + i/;


例子:


range/10, 15/;
[ 10, 11, 12, 13, 14, 15 ]

君笑尘

赞同来自:

一些不同范围功能的研究。
http://jsperf.com/javascript-range-tests
执行这些功能的不同方式。 当然,不是理想或详尽的名单,但应该有所帮助 :/

获胜者是。

..


function range/lowEnd,highEnd/{
var arr = [],
c = highEnd - lowEnd + 1;
while / c-- / {
arr[c] = highEnd--
}
return arr;
}
range/0,31/;


从技术上讲,他不是最快的 firefox, 但巨大的速度差异 /imho/ 在 chrome 补偿它。

观察多司令也很有意思 chrome 与数组的这些功能合作 firefox.

至少在铬 4 或者 5 一旦速度迅速

.

龙天

赞同来自:

您可以使用
https://lodash.com/docs#range
或者
http://underscorejs.org/#range
range

:


var range = require/'lodash/range'/
range/10/
// -> [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]


此外,如果您只需要一个一致的整数范围,您可以执行以下操作:


Array.apply/undefined, { length: 10 }/.map/Number.call, Number/
// -> [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]


在 ES6
range

可以实施
https://developer.mozilla.org/ ... yield
:


function* range/start=0, end=null, step=1/ {
if /end == null/ {
end = start;
start = 0;
}

for /let i=start; i < end; i+=step/ {
yield i;
}
}


此实现将内存保存在大序列的迭代中,因为它不需要将所有值归化为数组:


for /let i of range/1, oneZillion// {
console.log/i/;
}

君笑尘

赞同来自:

标准 Javascript 它没有用于生成范围的内置范围。 几个框架 javascript 添加对此类功能的支持,或者指定,您可以始终自己运行。

如果要仔细检查,那么最终资源
http://www.ecma-international. ... 2.htm
ECMA-262 .

涵秋

赞同来自:

也许这不是最好的方式。 但如果您想在代码的一行中获取数字范围。 例如, 10 - 50


Array/40/.fill/undefined/.map//n, i/ => i + 10/


其中40岁 /结尾 - 开始/ , 10是开始。 这应该回来

[10, 11, ..., 50

]

小姐请别说爱

赞同来自:

一个有趣的任务将写最多

短的

函数。 递归来到救援!


function r/a,b/{return a>b?[]:[a].concat/r/++a,b//}


通常,它在大范围内慢慢地工作,但幸运的是,量子计算机不远。

额外的奖金是它混淆了。 因为我们都知道隐藏窥探眼睛的代码是多么重要。

为了真正混淆这个功能,做到这一点:


function r/a,b/{return /a<b?[a,b].concat ++a,--b="" :a="" r="">b?[]:[a]/.sort/function/a,b/{return a-b}/}


</b?[a,b].concat>

詹大官人

赞同来自:

我会编码这样的东西:


function range/start, end/ {
return Array/end-start/.join/0/.split/0/.map/function/val, id/ {return id+start}/;
}

range/-4,2/;
// [-4,-3,-2,-1,0,1]

range/3,9/;
// [3,4,5,6,7,8]


他的行为与范围类似 Python:


>>> range/-4,2/
[-4, -3, -2, -1, 0, 1]

八刀丁二

赞同来自:

非常简约的实现,非常使用 ES6, 可以如下创建,吸引对静态方法的特别关注
https://developer.mozilla.org/ ... /from
:


const getRange = /start, stop/ => Array.from/
new Array//stop - start/ + 1/,
/_, i/ => i + start
/;

三叔

赞同来自:

range/start,end,step/

: s iteratrami. ES6

你只能问上下边界。

在这里,我们也有一个步骤。

您可以轻松创建生成功能。
range//

, 它可以用作迭代器。 这意味着您不需要预先生成整个数组。


function * range / start, end, step = 1 / {
let state = start;
while / state < end / {
yield state;
state += step;
}
return;
};


现在,您可以创建从迭代器中预先生成数组并返回列表的内容。 这对于占用阵列的函数非常有用。 为此,我们可以使用
Array.from//



const generate_array = /start,end,step/ =>
Array.from/ range/start,end,step/ /;


现在,您可以轻松生成静态数组,


const array1 = generate_array/1,10,2/;
const array1 = generate_array/1,7/;


但是什么时候愿意迭代器 /或者让您有机会使用迭代器/, 你也可以轻松创建它。


for / const i of range/1, Number.MAX_SAFE_INTEGER, 7/ / {
console.log/i/
}


特别注意

如果您正在使用
https://ramdajs.com/docs/#range
就像我一样。
https://lodash.com/docs/4.17.11#range

董宝中

赞同来自:

虽然不是来自

PHP

, 模仿
range

经过

Python

.


function range/start, end/ {
var total = [];

if /!end/ {
end = start;
start = 0;
}

for /var i = start; i < end; i += 1/ {
total.push/i/;
}

return total;
}

console.log/range/10//; // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log/range/0, 10//; // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log/range/5, 10//; // [5, 6, 7, 8, 9]

小姐请别说爱

赞同来自:

至于创建一个给定范围的数组,我使用它:


function range/start, stop/
{
var array = [];

var length = stop - start;

for /var i = 0; i <= length; i++/ {
array[i] = start;
start++;
}

return array;
}

console.log/range/1, 7//; // [1,2,3,4,5,6,7]
console.log/range/5, 10//; // [5,6,7,8,9,10]
console.log/range/-2, 3//; // [-2,-1,0,1,2,3]


显然,它不适用于字母阵列。

卫东

赞同来自:

使用
http://wiki.ecmascript.org/dok ... ators
,
http://kangax.github.io/es5-compat-table/es6/
:


var take = function /amount, generator/ {
var a = [];

try {
while /amount/ {
a.push/generator.next///;
amount -= 1;
}
} catch /e/ {}

return a;
};

var takeAll = function /gen/ {
var a = [],
x;

try {
do {
x = a.push/gen.next///;
} while /x/;
} catch /e/ {}

return a;
};

var range = /function /d/ {
var unlimited = /typeof d.to === "undefined"/;

if /typeof d.from === "undefined"/ {
d.from = 0;
}

if /typeof d.step === "undefined"/ {
if /unlimited/ {
d.step = 1;
}
} else {
if /typeof d.from !== "string"/ {
if /d.from < d.to/ {
d.step = 1;
} else {
d.step = -1;
}
} else {
if /d.from.charCodeAt/0/ < d.to.charCodeAt/0// {
d.step = 1;
} else {
d.step = -1;
}
}
}

if /typeof d.from === "string"/ {
for /let i = d.from.charCodeAt/0/; /d.step > 0/ ? /unlimited ? true : i <= d.to.charCodeAt/0// : /i >= d.to.charCodeAt/0//; i += d.step/ {
yield String.fromCharCode/i/;
}
} else {
for /let i = d.from; /d.step > 0/ ? /unlimited ? true : i <= d.to/ : /i >= d.to/; i += d.step/ {
yield i;
}
}
}/;


样本



例子 1.


take

只需要尽可能多地获得


take/10, range/ {from: 100, step: 5, to: 120} / /


回报


[100, 105, 110, 115, 120]


例子 2.


to

没必要


take/10, range/ {from: 100, step: 5} / /


回报


[100, 105, 110, 115, 120, 125, 130, 135, 140, 145]


takeAll

例子 3.


from

没必要


takeAll/ range/ {to: 5} / /


回报


[0, 1, 2, 3, 4, 5]


例子 4.


takeAll/ range/ {to: 500, step: 100} / /


回报


[0, 100, 200, 300, 400, 500]


例子 5.


takeAll/ range/ {from: 'z', to: 'a'} / /


回报


["z", "y", "x", "w", "v", "u", "t", "s", "r", "q", "p", "o", "n", "m", "l", "k", "j", "i", "h", "g", "f", "e", "d", "c", "b", "a"]

詹大官人

赞同来自:

...

使用发电机功能的更多范围。


function range/s, e, str/{
// create generator that handles numbers & strings.
function *gen/s, e, str/{
while/s <= e/{
yield /!str/ ? s : str[s]
s++
}
}
if /typeof s === 'string' && !str/
str = 'abcdefghijklmnopqrstuvwxyz'
const from = /!str/ ? s : str.indexOf/s/
const to = /!str/ ? e : str.indexOf/e/
// use the generator and return.
return [...gen/from, to, str/]
}

// usage ...
console.log/range/'l', 'w'//
//=> [ 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w' ]

console.log/range/7, 12//
//=> [ 7, 8, 9, 10, 11, 12 ]

// first 'o' to first 't' of passed in string.
console.log/range/'o', 't', "ssshhhooooouuut!!!!"//
// => [ 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 't' ]

// only lowercase args allowed here, but ...
console.log/range/'m', 'v'/.map/v=>v.toUpperCase////
//=> [ 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V' ]

// => and decreasing range ...
console.log/range/'m', 'v'/.map/v=>v.toUpperCase///.reverse///

// => ... and with a step
console.log/range/'m', 'v'/
.map/v=>v.toUpperCase///
.reverse//
.reduce//acc, c, i/ => /i % 2/ ? acc.concat/c/ : acc, []//

// ... etc, etc.


我希望它有用。

郭文康

赞同来自:

我的同事们 codegolfing 我想出了它 /ES6/,
包括的:


/s,f/=>[...Array/f-s+1/].map//e,i/=>i+s/


客房包容:


/s,f/=>[...Array/f-s/].map//e,i/=>i+s/

要回复问题请先登录注册