如何用 1 到 0 之间的数字填充二维数组?

我正在尝试用随机 1 填充二维数组并将我编写的代码归零


new Array(16).fill(null).map(()=>new Array(16).fill(Math.round(Math.random())));

这段代码的问题,我最终得到了类似的东西


0: (16) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

1: (16) [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

2: (16) [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

3: (16) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

4: (16) [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

5: (16) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

6: (16) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

7: (16) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

8: (16) [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

9: (16) [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

10: (16) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

11: (16) [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

12: (16) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

13: (16) [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

14: (16) [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

15: (16) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

我想要类似的东西


0: (16) [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1]

1: (16) [1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1]

2: (16) [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

3: (16) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]

4: (16) [0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1]

5: (16) [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

6: (16) [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

7: (16) [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

8: (16) [1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1]

9: (16) [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

10: (16) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

11: (16) [0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]

12: (16) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

13: (16) [0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

14: (16) [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

15: (16) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

我希望每个行都有一个随机数,而不是所有行的数字都相同。


炎炎设计
浏览 141回答 1
1回答

BIG阳

来自Array.prototype.fill():该fill()方法使用静态值填充数组从开始索引(默认为零)到结束索引(默认数组长度)的所有元素。因此,每个内部数组Math.round(Math.random())都填充了相同的值在下面的示例中,Math.random()被评估一次并且该静态值重复 5 次:console.log(Array(5).fill(Math.random()))相反,您可以Array.from()像这样使用嵌套:const createMatrix = length =>   Array.from({ length }, _ =>       Array.from({ length }, _ => Math.round(Math.random())))console.log(JSON.stringify(createMatrix(3)))console.log(JSON.stringify(createMatrix(6)))这是一个详细的版本:function createMatrix(n) {    // creates an arary with length = n    const arrayOfLengthN = Array.from({ length: n });        // map the array and create a 2D array    return arrayOfLengthN.map(a => Array.from({ length: n })                                 .map(b => Math.round(Math.random())))}console.log(JSON.stringify(createMatrix(3)))console.log(JSON.stringify(createMatrix(6)))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript