在PHP中,你可以做...
range(1, 3); // Array(1, 2, 3)
range("A", "C"); // Array("A", "B", "C")
Run Code Online (Sandbox Code Playgroud)
也就是说,有一个函数可以通过传递上限和下限来获取一系列数字或字符.
是否内置了JavaScript本身的内容?如果没有,我将如何实施它?
我正在尝试使用reduce()"整理"顺序组合一组数组,因此具有相似索引的项目在一起.例如:
input = [["one","two","three"],["uno","dos"],["1","2","3","4"],["first","second","third"]]
output = [ 'first','1','uno','one','second','2','dos','two','third','3','three','4' ]
Run Code Online (Sandbox Code Playgroud)
只要它们在一起,具有相似索引的项目的顺序无关紧要,因此结果'one','uno','1'...是如上所述.我想尽可能使用不可变变量.
我有办法:
const output = input.reduce((accumulator, currentArray, arrayIndex)=>{
currentArray.forEach((item,itemIndex)=>{
const newIndex = itemIndex*(arrayIndex+1);
accumulator.splice(newIndex<accumulator.length?newIndex:accumulator.length,0,item);
})
return accumulator;
})
Run Code Online (Sandbox Code Playgroud)
但它不是很漂亮而且我不喜欢它,特别是因为它在forEach方法中改变累加器的方式.我觉得必须有一个更优雅的方法.
我不敢相信之前没有人问过这个问题,但是我尝试了一堆不同的查询而无法找到它,所以请告诉我它是否在那里而我错过了它.有没有更好的办法?
为了澄清评论中的每个问题,我希望能够在不改变任何变量或数组的情况下执行此操作,因为我正在使用accumulator.splice和仅使用函数方法,例如.map,或者.reduce不使用类似的变异循环.forEach.
创建从数字 17 到数字 120 的数组的最快方法是什么?
[17,18,20,...,118,119,120]
Run Code Online (Sandbox Code Playgroud)
我尝试使用数组方法,但它以 0 开头,并从某些 resson 中切片,剪切最后一个数字而不是第一个数字。
export const ARR_OF_AGES = Array(121).fill().slice(16).map((x, i) => {
return { value: i, label: i }
})
Run Code Online (Sandbox Code Playgroud)