【问题标题】:Create unique pairs of numbers within a range and store as objects在一个范围内创建唯一的数字对并存储为对象
【发布时间】:2020-12-10 01:04:34
【问题描述】:

基本上,我想从数字 1 到 20 创建所有唯一的对象对组合。但至关重要的是,我不希望以不同的顺序在一对中重复相同的数字(所以不是一个完整的阶乘,例如不是: {num_set_one: 1, num_set_two: 2} {num_set_one: 2, num_set_two: 1})

我想要这样的东西:

array = [
{num_set_one: 1, num_set_two: 1}
{num_set_one: 1, num_set_two: 2}
{num_set_one: 1, num_set_two: 3}
{num_set_one: 1, num_set_two: 4}]
...
{num_set_one: 19, num_set_two: 20}
{num_set_one: 20, num_set_two: 20}
]

任何提示将不胜感激,谢谢!

【问题讨论】:

  • 你有我们可以构建的尝试或代码吗?

标签: javascript arrays object unique


【解决方案1】:

只需使用嵌套循环:

const array = [];
for (let i = 1; i <= 20; i ++) {
    for (let j = i; j <= 20; j ++) {
        array.push({num_set_one: i, num_set_two: j});
    }
}

【讨论】:

    猜你喜欢
    • 2019-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-15
    相关资源
    最近更新 更多