J. *_*Doe 3 javascript arrays numbers concatenation
我想在可读字符串中连接数字序列。连续数字应该像这样合并'1-4'。
我可以将具有所有数字的数组连接成一个完整的字符串,但是我无法合并/合并连续的数字。
我尝试使用几种条件将循环中的前一个和下一个值与当前值进行比较,if但是我似乎找不到合适的值来使其正常工作。
例子:
if(ar[i-1] === ar[i]-1){}
if(ar[i+1] === ar[i]+1){}
Run Code Online (Sandbox Code Playgroud)
我的代码如下所示:
if(ar[i-1] === ar[i]-1){}
if(ar[i+1] === ar[i]+1){}
Run Code Online (Sandbox Code Playgroud)
结果是: 1 - 2, 3, 4, 7, 8, 9, 13, 16, 17
最后,它应如下所示:1-4, 7-9, 13, 16-17。
编辑:我在@CMS'链接中为脚本使用了第一个答案。看起来很像@corschdi的代码段的较短版本:
var ar = [1,2,3,4,7,8,9,13,16,17];
var pages = ar[0];
var lastValue = ar[0];
for(i=1; i < ar.length; i++){
if(ar[i]-1 === lastValue){
pages = pages + ' - ' + ar[i];
}else{
pages = pages + ', ' + ar[i];
}
}
alert(pages);Run Code Online (Sandbox Code Playgroud)
In your code, lastValue never changes in the loop, so you're forever comparing against the first element in the array. Also, when you do find a match, you aren't yet ready to append to the pages result just yet--there might be more numbers to come.
One approach might be to keep a run of the current sequence of numbers (or just the first and last numbers in a run), and only append this run to the result string whenever we find a break in the sequence or hit the end of the string.
There are many ways to approach this, and I recommend checking other folks' answers at the Codewars: Range Extraction kata, which is (almost) identical to this problem.
Here's my solution:
const rangeify = a => {
const res = [];
let run = []
for (let i = 0; i < a.length; i++) {
run.push(a[i]);
if (i + 1 >= a.length || a[i+1] - a[i] > 1) {
res.push(
run.length > 1 ? `${run[0]}-${run.pop()}` : run
);
run = [];
}
}
return res.join(", ");
};
[
[1,2,3,4,7,8,9,13,16,17],
[],
[1],
[1, 2],
[1, 3],
[1, 2, 3, 8],
[1, 3, 4, 8],
[1, 1, 1, 1, 2, 3, 4, 5, 5, 16],
[-9, -8, -7, -3, -1, 0, 1, 2, 42]
].forEach(test => console.log(rangeify(test)));Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
117 次 |
| 最近记录: |