在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.
希望这有用。
其他回答
没有一个示例进行了测试,每个步骤都有一个生成递减值的选项。
export function range(start = 0, end = 0, step = 1) {
if (start === end || step === 0) {
return [];
}
const diff = Math.abs(end - start);
const length = Math.ceil(diff / step);
return start > end
? Array.from({length}, (value, key) => start - key * step)
: Array.from({length}, (value, key) => start + key * step);
}
测验:
import range from './range'
describe('Range', () => {
it('default', () => {
expect(range()).toMatchObject([]);
})
it('same values', () => {
expect(range(1,1)).toMatchObject([]);
})
it('step=0', () => {
expect(range(0,1,0)).toMatchObject([]);
})
describe('step=1', () => {
it('normal', () => {
expect(range(6,12)).toMatchObject([6, 7, 8, 9, 10, 11]);
})
it('reversed', () => {
expect(range(12,6)).toMatchObject([12, 11, 10, 9, 8, 7]);
})
})
describe('step=5', () => {
it('start 0 end 60', () => {
expect(range(0, 60, 5)).toMatchObject([0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55]);
})
it('reversed start 60 end -1', () => {
expect(range(55, -1, 5)).toMatchObject([55, 50, 45, 40, 35, 30, 25, 20, 15, 10, 5, 0]);
})
})
})
在Vue中循环0和长度之间的数字范围:
<div v-for="index in range" />
computed: {
range () {
let x = [];
for (let i = 0; i < this.myLength; i++)
{
x.push(i);
}
return x;
}
}
(from, to) => [...Array(to - from)].map((_,i)=> i + from)
数字
[...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归功于尼尔斯·彼得索恩和其他评论者)
我回顾了这里的答案,并注意到以下几点:
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]