在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(start_or_num, end = null, increment = 1) {
const end_check = end === null
const start = end_check ? 0 : start_or_num
const count = end_check ? start_or_num : Math.round((end - start) / increment) + 1
const filterFunc = end_check ? x => x >= start : x => x < end && x >= start
return [...Array.from(
Array(count).keys(), x => increment * (x - 1) + start
)
].filter(filterFunc)
}
// usage
// console.log(Range(4, 10, 2)) // [4, 6, 8]
// console.log(Range(5, 10 )) //[5, 6, 7, 8, 9]
// console.log(Range(10 ))// [0, 1, 2, 3, 4, 5, 6, 7, 8]
其他回答
我会这样编码:
function range(start, end) {
return Array(end-start).join(0).split(0).map(function(val, id) {return id+start});
}
range(-4,2);
// [-4,-3,-2,-1,0,1]
range(3,9);
// [3,4,5,6,7,8]
它的行为类似于Python范围:
>>> range(-4,2)
[-4, -3, -2, -1, 0, 1]
我刚刚通过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
它适用于字符和数字,通过可选步骤向前或向后移动。
var range = function(start, end, step) {
var range = [];
var typeofStart = typeof start;
var typeofEnd = typeof end;
if (step === 0) {
throw TypeError("Step cannot be zero.");
}
if (typeofStart == "undefined" || typeofEnd == "undefined") {
throw TypeError("Must pass start and end arguments.");
} else if (typeofStart != typeofEnd) {
throw TypeError("Start and end arguments must be of same type.");
}
typeof step == "undefined" && (step = 1);
if (end < start) {
step = -step;
}
if (typeofStart == "number") {
while (step > 0 ? end >= start : end <= start) {
range.push(start);
start += step;
}
} else if (typeofStart == "string") {
if (start.length != 1 || end.length != 1) {
throw TypeError("Only strings with one character are supported.");
}
start = start.charCodeAt(0);
end = end.charCodeAt(0);
while (step > 0 ? end >= start : end <= start) {
range.push(String.fromCharCode(start));
start += step;
}
} else {
throw TypeError("Only string and number types are supported");
}
return range;
}
jsFiddle。
如果扩充本机类型是您的事情,那么将其分配给Array.range。
var范围=函数(开始、结束、步骤){var范围=[];var typeofStart=启动类型;var typeofEnd=结束类型;如果(步骤==0){throw TypeError(“步长不能为零。”);}if(类型开始==“undefined”| |类型结束==“未定义”){throw TypeError(“必须传递开始和结束参数。”);}否则如果(typeofStart!=typeofEnd){throw TypeError(“开始和结束参数必须是相同的类型。”);}步骤类型==“未定义”&&(步骤=1);if(结束<开始){step=-步骤;}if(开始类型==“number”){while(步骤>0?结束>=开始:结束<=开始){范围.推(启动);开始+=步骤;}}否则if(typeofStart==“string”){如果(start.length!=1 | | end.length;=1){throw TypeError(“仅支持带有一个字符的字符串。”);}start=start.charCodeAt(0);end=end.charCodeAt(0);while(步骤>0?结束>=开始:结束<=开始){range.push(String.fromCharCode(开始));开始+=步骤;}}其他{throw TypeError(“仅支持字符串和数字类型”);}返回范围;}console.log(范围(“A”,“Z”,1));console.log(范围(“Z”,“A”,1));console.log(范围(“A”,“Z”,3));console.log(范围(0,25,1));console.log(范围(0,25,5));console.log(范围(20,5,5));
也可以使用生成器生成序列。不同之处在于序列中的每个值都是延迟加载的。spread运算符和for为结果工作。星号符号使函数成为生成器。
const range = function*(from,to) {
for(let i = from; i <= to; i++) yield I;
};
[...range(3,5)]// => [3, 4, 5]
可以如下创建大量使用ES6的相当简约的实现,特别注意Array.from()静态方法:
const getRange = (start, stop) => Array.from(
new Array((stop - start) + 1),
(_, i) => i + start
);