在循环中更改数组并从先前添加的项目开始



我想循环一个数组并添加到数组中,然后在循环中使用先前添加的项目。所以我想循环 1,4,1 并在 1 和 4 之间添加 0.5,然后回到 1。所以最终的字符串或数组将是:

1 1.5 2 2.5 3 3.5 4 等

问题是我可以添加到索引项,但不能添加到循环中的该项。第一个循环是 1,然后我加 1.5,第二个循环应该是 1.5,但循环将是 4。

base_string = '1,4,1';
base_string = base_string.split(',');
for (var i = 0; i < base_str.length; i++) {
// I add 1.5 to array and I want to use that the next loop, but the next loop is 4 instead
}

您可以减少给定的数组并通过取值来填充值以进行递增或递减。

var string = '1,4,1',
result = string
.split(',')
.map(Number)
.reduce((r, v) => {
if (!r) return [v];
let last = r[r.length - 1],
delta = v > last ? 0.5 : -0.5;
while (last + delta !== v) r.push(last += delta);
r.push(v);
return r;
}, undefined);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

let base_string = '1,4,1';
let base_array = base_string.split(',').map(i => +i);
let inc = 0.5; // the number to add in every step
let res = [];
let i = 0;
// Iterate till the last element is reached
while(i < base_array.length) {
// Iterate till there is some difference between adjacent items
while(Math.abs(base_array[i] - base_array[i+1]) > inc) {
res.push(base_array[i]);

if(base_array[i] < base_array[i+1]) base_array[i] += 0.5;
else base_array[i] -= 0.5;
}

i++;
}
res.push(base_array[i-1]); // add the last element
console.log(res.join(' '));

这应该适用于任何数组。

var base_string = '1,4,1,7,2';
base_string = base_string.split(',');
var new_string = []; 
for(var i=0; i<base_string.length-1; i++){
if(base_string[i+1]>base_string[i]){
for(var j=parseInt(base_string[i]); j<parseInt(base_string[i+1]); j+=.5){
new_string.push((j))
}
}
else  if(base_string[i+1]<base_string[i]){
for(var j=parseInt(base_string[i]); j>=parseInt(base_string[i+1]); j-=.5){
new_string.push((j))
}
}
}
console.log("new_string: "+new_string);

我认为您可以使用两个for循环来做到这一点,只需维护一个direction变量即可将计数器指向正确的方向:

let arr = [1, 4, 1]
let res = [arr[0]]
let step = 0.5
for (let i = 1; i < arr.length; i++) {
let direction = arr[i] > arr[i - 1] ? 1 : -1
for (let j = (direction * arr[i - 1]) + step; j <= (direction * arr[i]); j += step) {
res.push(j * direction)
}
}
console.log(res)

你可以像这样使用"reduce"函数:

var base_string = '1,2,3,4';
base_string = base_string.split(',').reduce((a, v, i, ar) => {
if (i === 1) {
// an array is created using the first two values of original the array
return [+a, +a + 0.5, +v, +v + 0.5];
}
// after index 2 you add an extra item +0.5
a.push(+v);
a.push(+v + 0.5);
return a;
});
console.log(base_string);

这将为您提供所需的输出:

[1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5]

请注意,在每个值之前都添加了加号(+),那是因为它们是字符串值,因此需要将它们转换为数字。

最新更新