Javascript-创建带有两个参数的函数并返回2d数组

我需要编写一个带有两个参数的函数-行和列。此函数的目的是返回具有给定数字和行的2d数组。我需要通过使用函数返回数组。这是一个代码:


我是一个初学者,我们将非常感谢您的每一个反馈。:-)


我已经检查过StackOverflow,我已经尝试过用Google搜索它,检查适当的网站-不幸的是,没有运气


function create2Darray(A) {

            var columns = [];

            var rows = Math.sqrt(A.length);

            for (var i = 0; i < rows; i++) {

                  columns[i] = [];

                  for (var j = 0; j < rows; j++) {

                        columns[i][j] = A[i * rows + j];

                  }

            }

            return columns;

      }


翻过高山走不出你
浏览 246回答 2
2回答

慕桂英4014372

您可以使用Array.from具有长度的对象,并使用第二个参数映射内部数组。const&nbsp; &nbsp; getArray = (l, w) => Array.from({ length: l }, (_, i) =>&nbsp; &nbsp; &nbsp; &nbsp; Array.from({ length: w }, (_, j) => i * w + j));console.log(getArray(3, 2));.as-console-wrapper { max-height: 100% !important; top: 0; }

慕仙森

您的问题陈述与您尝试的代码不匹配。看来您想将一维数组转换为2D数组。您的代码很好。但是问题是,Math.sqrt(A.length);可能返回floati * rows + j并将变为float,而数组没有float索引。只是Math.ceil()用来修复function create2Darray(A) {&nbsp; &nbsp; &nbsp;var columns = [];&nbsp; &nbsp; &nbsp;var rows = Math.ceil(Math.sqrt(A.length));&nbsp; &nbsp; &nbsp;for (var i = 0; i < rows; i++) {&nbsp; &nbsp; &nbsp; &nbsp; columns[i] = [];&nbsp; &nbsp; &nbsp; &nbsp; for (var j = 0; j < rows; j++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; columns[i][j] = A[i * rows + j];&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return columns;}console.log(create2Darray([1,2,3,4,5,6,7,8]))以下两个解决方案适用于需要长度和宽度的函数。function array(l,w){&nbsp; let res = [];&nbsp; for(let i = 0; i < l;i++){&nbsp; &nbsp; res[i] = [];&nbsp; &nbsp; for(let j = 0; j < w; j++){&nbsp; &nbsp; &nbsp; res[i][j] = (w * i) + j&nbsp; &nbsp; }&nbsp; }&nbsp; return res;}console.log(JSON.strigify(array(3,2)))可以使用嵌套制作衬垫 map()const array = (l,w) => [...Array(l)].map((x,i) => [...Array(w)].map((x,j) => (i*w) + j))console.log(JSON.stringify(array(3,2)))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript