在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本机是否有内置的功能?如果没有,我将如何实施?
当前回答
方便的函数来完成这个技巧,请运行下面的代码片段
功能范围(开始、结束、步长、偏移){var len=(数学.abs(结束-开始)+((偏移量||0)*2))/(步骤||1)+1;var方向=开始<结束?1 : -1;var startingPoint=开始-(方向*(偏移||0));var stepSize=方向*(步骤||1);return Array(len).fill(0).map(函数(_,索引){return startingPoint+(stepSize*索引);});}console.log('范围(1,5)=>'+范围(1、5));console.log('范围(5,1)=>'+范围(5、1));console.log('范围(5,5)=>'+范围(5、5));console.log('范围(-5,5)=>'+范围(-5、5));console.log('范围(-10,5,5)=>'+范围(-10、5,5));console.log('范围(1,5,1,2)=>'+范围(1、5、1,2;
下面是如何使用它
范围(开始,结束,步长=1,偏移=0);
包括-前进档(5,10)//[5,6,7,8,9,10]包括-向后范围(10,5)//[10,9,8,7,6,5]后退范围(10,2,2)//[10,8,6,4,2]排他-前进范围(5,10,0,-1)//[6,7,8,9]而不是5,10本身偏移-扩展范围(5,10,0,1)//[4,5,6,7,8,9,10,11]偏移-收缩范围(5,10,0,-2)//[7,8]步进-扩展范围(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)计算结果数组的长度,以使其更简单(两个方向上的差值*offset/step)获得长度后,我们使用newArray(length).fill(0)创建一个带有初始化值的空数组;在此处检查现在我们有一个数组[0,0,0,..],其长度是我们想要的。我们对其进行映射,并使用array.map(function(){})返回一个具有所需值的新数组var方向=开始<结束?1 : 0; 显然,如果起点不小于终点,我们就需要后退。我的意思是从0到5,反之亦然在每次迭代中,startingPoint+stepSize*索引将为我们提供所需的值
其他回答
这里是一个范围函数的定义,它的行为与Python的范围类型完全相同,只是这个函数不是懒惰的。把它变成发电机应该很容易。
范围构造函数的参数必须是数字。如果省略step参数,则默认为1。如果省略了start参数,则默认为0。如果步骤为零,则会引发错误。
range = (start, stop, step=1) => {
if(step === 0) throw new Error("range() arg 3 must not be zero");
const noStart = stop == null;
stop = noStart ? start : stop;
start = noStart ? 0 : start;
const length = Math.ceil(((stop - start) / step));
return Array.from({length}, (_, i) => (i * step) + start);
}
console.log(range(-10, 10, 2));
//output [Array] [-10,-8,-6,-4,-2,0,2,4,6,8]
console.log(range(10));
// [Array] [0,1,2,3,4,5,6,7,8,9]
console.log(3, 12);
// [Array] [3,4,5,6,7,8,9,10,11]
使用TypeScript设置(应用程序范围):
declare global {
interface Function {
range(count: number, start_with: number): number[];
}
}
Function.prototype.range = function (
count: number,
start_with: number = 0
): number[] {
return [...Array(count).keys()].map((key) => key + start_with);
};
使用JS设置:
Function.prototype.range = function(count, start_with=0){
return [...Array(count).keys()].map((key) => key + start_with);
}
使用示例:
Function.range(2,0) //Will return [0,1]
Function.range(2,1) //Will return [1,2]
Function.range(2,-1) //Will return [-1,0]
下面是实现自己的可迭代范围函数的方法。
//实施范围功能范围(开始、结束){返回{从:开始,结束,[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}
我刚刚通过Object.defineProperty在Array上创建了这个polyfill,以创建整数或字符串的范围。Object.defineProperty是创建polyfills的一种更安全的方法。
更安全的polyfill
if (!Array.range) {
Object.defineProperty(Array, 'range', {
value: function (from, to, step) {
if (typeof from !== 'number' && typeof from !== 'string') {
throw new TypeError('The first parameter should be a number or a character')
}
if (typeof to !== 'number' && typeof to !== 'string') {
throw new TypeError('The second parameter should be a number or a character')
}
var A = []
if (typeof from === 'number') {
A[0] = from
step = step || 1
while (from + step <= to) {
A[A.length] = from += step
}
} else {
var s = 'abcdefghijklmnopqrstuvwxyz'
if (from === from.toUpperCase()) {
to = to.toUpperCase()
s = s.toUpperCase()
}
s = s.substring(s.indexOf(from), s.indexOf(to) + 1)
A = s.split('')
}
return A
}
})
} else {
var errorMessage = 'DANGER ALERT! Array.range has already been defined on this browser. '
errorMessage += 'This may lead to unwanted results when Array.range() is executed.'
console.log(errorMessage)
}
示例
Array.range(1, 3)
// Return: [1, 2, 3]
Array.range(1, 3, 0.5)
// Return: [1, 1.5, 2, 2.5, 3]
Array.range('a', 'c')
// Return: ['a', 'b', 'c']
Array.range('A', 'C')
// Return: ['A', 'B', 'C']
Array.range(null)
Array.range(undefined)
Array.range(NaN)
Array.range(true)
Array.range([])
Array.range({})
Array.range(1, null)
// Return: Uncaught TypeError: The X parameter should be a number or a character
一个可以在任一方向工作的衬垫:
const range = (a,b)=>Array(Math.abs(a-b)+1).fill(a).map((v,i)=>v+i*(a>b?-1:1));
请参阅实际操作:
常量范围=(a,b)=>数组(数学.abs(a-b)+1).fill(a).map((v,i)=>v+i*(a>b?-1:1));console.log(范围(1,4));console.log(范围(4,1));