使用循环操作数组中的数组
Manipulation using loop for array within array
[['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('-----------------');
相关文章:
- 如何在映射数组中添加换行符
- javascript结合了数组和字典
- 需要帮助设置json数组
- 不能从angular2中的子组件指定父组件中的数组
- 使用JS将数组转换为json对象
- 数组在递归方法中设置为null
- knockoutjs可观察数组
- Javascript-如何读取json文件中的列并将其保存在Javascript数组中
- 将数组从PHP传递到Javascript
- JavaScript数组排序(函数)用于对表行进行排序,而不是排序
- 在函数中添加数组元素的数值
- 无法通过数组映射绑定
- javascript中的数组出错
- 如何使用 node.js 比较两个 json 数组
- Javascript(Angular)从一个对象数组到第二个数组查找值
- 根据id将json数组组合为一个json数组
- 翻转操作数时,添加带有空对象的空数组会产生不同的结果
- 从文本字符串使用 javascript 创建数组并操作数据以满足您的需求
- 使用循环操作数组中的数组
- 回调&操作数组,但返回未定义的数组