在PHP中,您可以。。。
range(1, 3); // Array(1, 2, 3)
range("A", "C"); // Array("A", "B", "C")
也就是说,有一个函数可以通过传递上下限来获得一系列数字或字符。
JavaScript本机是否有内置的功能?如果没有,我将如何实施?
在PHP中,您可以。。。
range(1, 3); // Array(1, 2, 3)
range("A", "C"); // Array("A", "B", "C")
也就是说,有一个函数可以通过传递上下限来获得一系列数字或字符。
JavaScript本机是否有内置的功能?如果没有,我将如何实施?
当前回答
…更大范围,使用生成器功能。
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.
希望这有用。
其他回答
您还可以执行以下操作:
const range = Array.from(Array(size)).map((el, idx) => idx+1).slice(begin, end);
使用范围([start,]stop[,step])签名完成ES6实现:
function range(start, stop, step=1){
if(!stop){stop=start;start=0;}
return Array.from(new Array(int((stop-start)/step)), (x,i) => start+ i*step)
}
如果要自动负步进,请添加
if(stop<start)step=-Math.abs(step)
或者更简单地说:
range=(b, e, step=1)=>{
if(!e){e=b;b=0}
return Array.from(new Array(int((e-b)/step)), (_,i) => b<e? b+i*step : b-i*step)
}
如果你有巨大的射程,看看保罗·莫雷蒂的发电机方法
这个也反过来。
const range = ( a , b ) => Array.from( new Array( b > a ? b - a : a - b ), ( x, i ) => b > a ? i + a : a - i );
range( -3, 2 ); // [ -3, -2, -1, 0, 1 ]
range( 1, -4 ); // [ 1, 0, -1, -2, -3 ]
可以使用带有数组、for循环和Math.random()变量的函数来解决这个问题。for循环将数字推入数组,数组将包含您范围内的所有数字。然后Math.random()根据数组的长度随机选择一个。
function randNumInRange(min, max) {
var range = []
for(var count = min; count <= max; count++) {
range.push(count);
}
var randNum = Math.floor(Math.random() * range.length);
alert(range[randNum]);
}
function check(){
var correct=true;
for(var i=0; i<arguments.length; i++){
if(typeof arguments[i] != "number"){
correct=false; } } return correct; }
//------------------------------------------
function range(start,step,end){
var correct=check(start,step,end);
if(correct && (step && end)!=0){
for(var i=start; i<=end; i+=step)
document.write(i+" "); }
else document.write("Not Correct Data"); }