使用循环操作数组中的数组

Manipulation using loop for array within array

本文关键字:数组 操作数 操作 循环      更新时间:2023-09-26
[['red','yellow'],['xl','xxl']]

上面是一组变型的衣服,下面是如何打印4套组合:

red xl, red xxl, yellow xl and yellow xxl

这看起来很简单,但因为它可能像另一个数组(或更多)的数据,我不能做data[0]或data[1]在这种情况下

应该可以:

// data to process and print
var data = [['red','yellow'],['xl','xxl'], ['boy', 'girl']];
var combinations = [], // will hold the running processed strings as we iterate
    temp = [], // temporary array
    isFirstPropSet = true; // flag to determine if we are processing the first property set (colors in this case)
// for each property set
data.forEach(function(datum) {
  // if it isn't the first property set, make a copy into temp and reset our combinations array
  if (!isFirstPropSet) {
    temp = combinations.splice(0);
    combinations = [];
  }
  // for each property in the current property set
  datum.forEach(function(prop) {
    // if it is the first property set, simply add it to the current running list
    if (isFirstPropSet) {
      combinations.push(prop);
    } else {
      // otherwise for each of the previous items, lets append the new property
      temp.forEach(function(comb) {
        combinations.push(comb + ' ' + prop);
      });
    }
  });
  // make sure to unset our flag after processing the first property set
  isFirstPropSet = false;
});
// print out all the combinations
combinations.forEach(function(comb) {
  console.log(comb);
});
console.log('-----------------');