创建JS数组,其中包含重复值

3

我想询问一种创建此数组的高效方法:

[
    1, 1, 1, 1, 1, 1,
    2, 2, 2, 2, 2, 2,
    3, 3, 3, 3, 3, 3
    ...
    n, n, n, n, n, n
]

每6个项目后,数字加1++。

function createFaces(n){
    var array = [];
    var l = 1; 
    while(n > 0){
        for(var i = 0; i < 6; i++){
            array.push(l)
        }
        l++;
        n--;
    }
    return array;
}

您想添加多少行? - GrumpyCrouton
无论是什么(例如6),都没有关系。 - Bartek
1
你的实现有什么问题? - Fallenreaper
嗨,你可以在那种类型的练习中使用递归函数。 - Angel
也许不是你想要的,但是你可以通过使用两个for循环来摆脱l++n++:https://jsfiddle.net/59nqskpb/1/ - Ivar
显示剩余2条评论
4个回答

2
你可以使用 Array.from 和一个值函数。

function createFaces(n) {
    return Array.from({ length: 6 * n }, (_, i) => Math.floor(i / 6) + 1);
}

console.log(createFaces(7));
.as-console-wrapper { max-height: 100% !important; top: 0; }


使用 Array.from 的不错方法。 - Ele

1

要创建一个大小为 n,填充有值 v 的数组,您可以执行以下操作

Array(n).fill(v);

在你的函数上下文中:
function createFaces(n){
    var array = [];
    for (var i=1; i <= n; i++) {
      array = array.concat(Array(6).fill(i));
    }
    return array;
}

这也创建了一个数组的数组,这并不完全是OP的代码所做的。要做完全相同的事情,for循环内部的行应该是array = array.concat(Array(6).fill(i)); - Herohtar
哎呀,我看到了一个不存在的数组的数组。是的,要连接(concat)。 - James

0
如果您想要一个平坦的数组...

function createFaces(n, x){
    for(var i=0, a=[]; i<n; a.push(...Array(x).fill(i)) && i++){}
    return a;
}

console.log(createFaces(7, 6));


0

使用Array.prototype.map()函数

let fill = function(length, threshold) {
  let i = 1;
  return new Array(length * threshold).fill().
            map((_, idx) => 
                (idx + 1) % threshold === 0 ? i++ : i);
};

console.log(fill(7, 6));


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接