【问题标题】:Manipulation using loop for array within array [duplicate]使用数组内的循环进行操作[重复]
【发布时间】:2015-08-18 01:54:54
【问题描述】:
[['red','yellow'],['xl','xxl']]

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

red xl, red xxl, yellow xl and yellow xxl

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

【问题讨论】:

  • 打印是什么意思?到控制台窗口?到 HTML?
  • 我添加了一个不需要下划线库并且应该易于阅读的答案...以防万一您仍然需要它。

标签: javascript jquery arrays loops


【解决方案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('-----------------');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2019-03-05
    相关资源
    最近更新 更多