在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本机是否有内置的功能?如果没有,我将如何实施?
当前回答
我在for循环中使用条件三元运算符(不过没有参数测试)。
function range(start,end,step){
var resar = [];
for (var i=start;(step<0 ? i>=end:i<=end); i += (step == undefined ? 1:step)){
resar.push(i);
};
return resar;
};
其他回答
对于行为类似python range()函数的函数,请使用以下命令:
function range(min=0, max=null){
if(max === null){
max=min;
min=0;
}
var rg=[...Array(max).keys()];
return rg.slice(min,max);
}
我最喜欢的新形式(ES2015)
Array(10).fill(1).map((x, y) => x + y)
如果您需要一个带有步骤参数的函数:
const range = (start, stop, step = 1) =>
Array(Math.ceil((stop - start) / step)).fill(start).map((x, y) => x + y * step)
MDN文件建议的另一种可能的实施方式:
// Sequence generator function
// (commonly referred to as "range", e.g. Clojure, PHP etc)
const range = (start, stop, step) =>
Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step))
/**
* @param {!number|[!number,!number]} sizeOrRange Can be the `size` of the range (1st signature) or a
* `[from, to]`-shape array (2nd signature) that represents a pair of the *starting point (inclusive)* and the
* *ending point (exclusive)* of the range (*mathematically, a left-closed/right-open interval: `[from, to)`*).
* @param {!number} [fromOrStep] 1st signature: `[from=0]`. 2nd signature: `[step=1]`
* @param {!number} [stepOrNothing] 1st signature: `[step=1]`. 2nd signature: NOT-BEING-USED
* @example
* range(5) ==> [0, 1, 2, 3, 4] // size: 5
* range(4, 5) ==> [5, 6, 7, 8] // size: 4, starting from: 5
* range(4, 5, 2) ==> [5, 7, 9, 11] // size: 4, starting from: 5, step: 2
* range([2, 5]) ==> [2, 3, 4] // [2, 5) // from: 2 (inclusive), to: 5 (exclusive)
* range([1, 6], 2) ==> [1, 3, 5] // from: 1, to: 6, step: 2
* range([1, 7], 2) ==> [1, 3, 5] // from: 1, to: 7 (exclusive), step: 2
* @see {@link https://stackoverflow.com/a/72388871/5318303}
*/
export function range (sizeOrRange, fromOrStep, stepOrNothing) {
let from, to, step, size
if (sizeOrRange instanceof Array) { // 2nd signature: `range([from, to], step)`
[from, to] = sizeOrRange
step = fromOrStep ?? 1
size = Math.ceil((to - from) / step)
} else { // 1st signature: `range(size, from, step)`
size = sizeOrRange
from = fromOrStep ?? 0
step = stepOrNothing ?? 1
}
return Array.from({length: size}, (_, i) => from + i * step)
}
示例:
控制台日志(范围(5),//[0,1,2,3,4]//size:5范围([2,5]),//[2,3,4]//[2、5)//从:2(含)到:5(不含)范围(4,2),//[2,3,4,5]//大小:4,从:2开始范围([1,6],2),//[1,3,5]//从:1到:6,步骤:2范围([1,7],2),//[1,3,5]//从:1到:7(不含),步骤:2)<脚本>函数范围(sizeOrRange、fromOrStep、stepOrNothing){让从、到、步长、大小if(sizeOrRange instanceof Array){//第二个签名:`range([from,to],step)`[from,to]=sizeOrRange步骤=来自或步骤??1.size=数学ceil((to-from)/步长)}else{//第一个签名:`range(大小,从,步)`size=sizeOrRangefrom=来自或步骤??0step=stepOrNothing??1.}return Array.from({length:size},(_,i)=>from+i*step)}</script>
我回顾了这里的答案,并注意到以下几点:
JavaScript没有解决此问题的内置解决方案某些答案生成大小正确但值错误的数组例如,让arr=Array.from({length:3});//给出[null,null,null]然后,使用映射函数将错误的值替换为正确的值例如arr.map((e,i)=>i);//给出[0,1,2]需要数学来移动数字范围,以满足从。。符合要求。例如arr.map((e,i)=>i+1);//给出[1,2,3]对于问题的字符串版本,需要charCodeAt和fromCharCode将字符串映射到一个数字,然后再返回到一个字符串。例如arr.map((e,i)=>String.fromCharCode(i+“A”.charCodeAt(0));//给出[“A”、“B”、“C”]
有一些基于以上部分或全部的简单到花哨的实现。当他们试图将整数和字符串解打包到一个函数中时,答案变得复杂起来。对我来说,我选择在它们自己的函数中实现整数和字符串解决方案。我证明这是合理的,因为在实践中,你会知道你的用例是什么,你会直接使用适当的函数。如果您想间接调用包装器函数,我也会提供它。
让rangeInt=(from,to)=>Array.from({length:to from+1},(e,i)=>i+from);let rangeChar=(from,to)=>数组.from({length:to.charCodeAt(0)-from.charCodeAt(0)+1},(e,i)=>字符串.fromCharCode(i+from.charCode At(1)));让范围=(从,到)=>(typeof(from)==“string”&&typeof(to)===“string”)? rangeChar(从,到):(!to)?rangeInt(0,from-1):范围Int(从,到);console.log(rangeInt(1,3));//给出[1,2,3]console.log(rangeChar(“A”,“C”));//给出[“A”、“B”、“C”]console.log(范围(1,3));//给出[1,2,3]console.log(范围(“A”、“C”));//给出[“A”、“B”、“C”]console.log(范围(3));//给出[0,1,2]
d3还具有内置范围功能。
看见https://github.com/d3/d3-array#range:
d3.范围([开始,]停止[,步骤])
生成包含算术级数的数组,类似于Python内置范围。此方法通常用于迭代一系列数值或整数值,例如数组中的索引。与Python版本不同,参数不需要是整数,但如果是由于浮点精度,则结果更可预测。如果省略步骤,则默认为1。
例子:
d3.range(10)
// returns [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]