用于根据先前值自动添加值的JavaScript循环

时间:2018-05-28 10:35:40

标签: javascript php jquery arrays loops

我从PHP数组获取值并存储在JavaScript变量数组中。

var js_array = [<?php echo '"'.implode('","', $count_common_months_arr).'"' ?>]; 
/* Result for js_array is : 5,4,4,5,4,4,5,4,4,5,4,4 */
var table_data_array = [0.10,0.15,0.10,0.10,0.90,2.50,0.10,0.90,0.90,0.40,0.30,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,];

我希望使用循环对数组进行切片,以便通过使用jQuery或JavaScript循环获得如下所示。

table_data_array.slice(0, 5);   start_value = 0; end = 5(first value in js_array) 
/* Note: Taking End values from js_array variable */
table_data_array.slice(5, 9);   start = 5; end = 5+4(second value in js_array) = 9;
table_data_array.slice(9, 13);  start_value = 9; end_value = 9+4(third value in js_array) = 13;
table_data_array.slice(13, 18); start_value = 13; end_value = 13+5(fourth value in js_array) = 18;
table_data_array.slice(18, 22); start_value = 18; end_value = 18+4(fifth value in js_array) = 22;
table_data_array.slice(22, 26); start_value = 22; end_value = 22+4(sixth value in js_array) = 26;
table_data_array.slice(26, 31); start_value = 26; end_value = 26+5(seventh value in js_array) = 31;
and so on...

if we execute table_data_array.slice(0, 5) /* 0.10,0.15,0.10,0.10,0.90 */
if we execute table_data_array.slice(5, 9) /* 2.50,0.10,0.90,0.90 */
and so..on..

我使用了下面的循环,并没有找到任何逻辑来获得上述结果。

for (i = 0; i <= js_array.length; i++) {
        var end = js_array[i];
        var start = 0;  
        console.log(table_data_array.slice(start, end));
    }

请帮帮我..我是这个节目的新手

1 个答案:

答案 0 :(得分:0)

要以这种方式拆分数组并创建一个包含这些切片的新数组,您可以使用Array.prototype.reduce结合此Array.prototype.splice

const js_array = [5,4,4,5,4];
const table_data_array = [0.10,0.15,0.10,0.10,0.90,2.50,0.10,0.90,0.90,0.40,
  0.30,0.10,0.15,0.10,0.10,0.90,2.50,0.10,0.90,0.90,0.40,0.30];


const result = js_array.reduce((acc, v) =>
  acc.concat([table_data_array.splice(0, v)]), []);

console.log(result);

如果您真的想使用循环,那么您可以这样做。

const js_array = [5,4,4,5,4];
const table_data_array = [0.10,0.15,0.10,0.10,0.90,2.50,0.10,0.90,0.90,0.40,
  0.30,0.10,0.15,0.10,0.10,0.90,2.50,0.10,0.90,0.90,0.40,0.30];

let counter = 0;

for (let i = 0; i < js_array.length; i++) {
  let slice = [];
  for (let j = 0; j < js_array[i]; j++) {
    slice.push(table_data_array[counter++]);
  }
  console.log(slice);
  slice = [];
}