数组未在 java 脚本中作为参数传递。

我有一个函数,它应该将(n * n)网格作为参数并输出4 nos的最大乘积。所有行。(项目欧拉问题11的一部分)。当我尝试运行它给我的代码时,


TypeError: Cannot read property 'length' of undefined

我在这里做错了什么?(我是初学者,所以如果我有任何愚蠢的错误,请告诉我。


这是我的代码:


const grid = [

  [40, 17, 81, 18, 57],

  [74, 4, 36, 16, 29],

  [36, 42, 69, 73, 45],

  [51, 54, 69, 16, 92],

  [7, 97, 57, 32, 16]

];


function largestGridProduct(arr) {

  let product = 1 , maxProduct = 1;

  for(let i=0 ; i<arr.length ; i++){

    for(let j=0 ; j<arr.length-3 ; j++){

      product = grid[i][j] * grid[i][j+1] * grid[i][j+2] * grid[i][j+3];

      if(product > maxProduct){

        maxProduct = product;

      }

    }

  }

  return maxProduct;

}


console.log(largestGridProduct(grid));

那么我在这里做错了什么?


GCT1015
浏览 90回答 3
3回答

米脂

您没有返回函数中的任何内容...顺便说一句,您可以使它更容易。请参阅此内容:[&nbsp; [40, 17, 81, 18, 57],&nbsp; [74, 4, 36, 16, 29],&nbsp; [36, 42, 69, 73, 45],&nbsp; [51, 54, 69, 16, 92],&nbsp; [7, 97, 57, 32, 16]&nbsp;].reduce((max, a2) => {&nbsp; const val = a2.reduce((a, b) => {&nbsp; &nbsp;return Math.max(a, b);&nbsp;});&nbsp;return Math.max(val, max);&nbsp;}, 0)它使用箭头函数 (es6) 和数组缩减。这将返回所有输入数组的最大值。

慕婉清6462132

像这样工作:)&nbsp; &nbsp;if(product > maxProduct){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return&nbsp; product = maxProduct;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; return&nbsp; maxProduct;&nbsp; &nbsp; }&nbsp; }}

DIEA

这是一个愚蠢的错误,我在函数中使用变量名称“grid”而不是“arr”。顺便说一句,谢谢大家。好的,这是我的工作代码:-const grid = [&nbsp; [40, 17, 81, 18, 57],&nbsp; [74, 4, 36, 16, 29],&nbsp; [36, 42, 69, 73, 45],&nbsp; [51, 54, 69, 16, 92],&nbsp; [7, 97, 57, 32, 16]];function largestGridProduct(arr) {&nbsp; let product = 1 , maxProduct = 1;&nbsp; for(let i=0 ; i<arr.length ; i++){&nbsp; &nbsp; for(let j=0 ; j<arr.length-3 ; j++){&nbsp; &nbsp; &nbsp; product = arr[i][j] * arr[i][j+1] * arr[i][j+2] * arr[i][j+3];&nbsp; &nbsp; &nbsp; if(product > maxProduct){&nbsp; &nbsp; &nbsp; &nbsp; maxProduct = product;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; }&nbsp; return maxProduct;}console.log(largestGridProduct(grid));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript