在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本机是否有内置的功能?如果没有,我将如何实施?
当前回答
我回顾了这里的答案,并注意到以下几点:
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]
Python风格的方式:
range = (start, end, step) => {
let arr = []
for(let n=start;n<end;n+=(step||1)) arr.push(n)
return arr;
}
要紧密复制的类型脚本函数
/**
* Create a generator from 0 to stop, useful for iteration. Similar to range in Python.
* See: https://stackoverflow.com/questions/3895478/does-javascript-have-a-method-like-range-to-generate-a-range-within-the-supp
* See: https://docs.python.org/3/library/stdtypes.html#ranges
* @param {number | BigNumber} stop
* @returns {Iterable<number>}
*/
export function range(stop: number | BigNumber): Iterable<number>
/**
* Create a generator from start to stop, useful for iteration. Similar to range in Python.
* See: https://stackoverflow.com/questions/3895478/does-javascript-have-a-method-like-range-to-generate-a-range-within-the-supp
* See: https://docs.python.org/3/library/stdtypes.html#ranges
* @param {number | BigNumber} start
* @param {number | BigNumber} stop
* @returns {Iterable<number>}
*/
export function range(
start: number | BigNumber,
stop: number | BigNumber,
): Iterable<number>
/**
* Create a generator from start to stop while skipping every step, useful for iteration. Similar to range in Python.
* See: https://stackoverflow.com/questions/3895478/does-javascript-have-a-method-like-range-to-generate-a-range-within-the-supp
* See: https://docs.python.org/3/library/stdtypes.html#ranges
* @param {number | BigNumber} start
* @param {number | BigNumber} stop
* @param {number | BigNumber} step
* @returns {Iterable<number>}
*/
export function range(
start: number | BigNumber,
stop: number | BigNumber,
step: number | BigNumber,
): Iterable<number>
export function* range(a: unknown, b?: unknown, c?: unknown): Iterable<number> {
const getNumber = (val: unknown): number =>
typeof val === 'number' ? val : (val as BigNumber).toNumber()
const getStart = () => (b === undefined ? 0 : getNumber(a))
const getStop = () => (b === undefined ? getNumber(a) : getNumber(b))
const getStep = () => (c === undefined ? 1 : getNumber(c))
for (let i = getStart(); i < getStop(); i += getStep()) {
yield i
}
}
下面是实现自己的可迭代范围函数的方法。
//实施范围功能范围(开始、结束){返回{从:开始,结束,[Symbol.iiterator](){this.current=this.from;返回此;},next(){if(this.current<=this.to){返回{done:false,值:this.current++};}其他{返回{done:true};}}};}//迭代每个值for(设范围数(1,5)){console.log(num);//1, 2, 3, 4, 5}
数字
[...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 => 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_.range()函数
_.range(10);
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
_.range(1, 11);
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
_.range(0, 30, 5);
=> [0, 5, 10, 15, 20, 25]
_.range(0, -10, -1);
=> [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
String.fromCharCode(..._.range('A'.charCodeAt(0), 'D'.charCodeAt(0) + 1));
=> "ABCD"
没有库的旧非es6浏览器:
Array.apply(null, Array(5)).map(function (_, i) {return i;});
=> [0, 1, 2, 3, 4]
console.log([…Array(5).keys()]);
(ES6归功于尼尔斯·彼得索恩和其他评论者)