【问题标题】:Multiplying all array elements in 2 dimensional array with a number [closed]将二维数组中的所有数组元素乘以一个数字[关闭]
【发布时间】:2021-09-23 19:37:22
【问题描述】:

function multiplyer(...arr){
    let res=[],product=1;
    
    for(var j=arr.length-1;j>=0;j--){
      
      res.unshift(arr[j].map(item=>item*product))
      product*=10
    }
    return res;
  }
  console.log(multiplyer([[2,3][3,5]]))
  

我期待像[[20,30][3,5]] 这样的东西,但我认为我在访问二维数组的元素时遇到了问题。结果为[ [ NaN ] ]

【问题讨论】:

标签: javascript arrays array.prototype.map


【解决方案1】:

对于一个问题,[ [ 2, 3 ][ 3, 5 ] ] 需要一个额外的逗号才能使其成为二维数组:[ [ 2, 3 ], [ 3, 5 ] ]

另一个问题是函数定义中的一个不必要的扩展运算符 (...) 会弄乱函数。

function multiplyer(arr) {
  let res = [],
    product = 1;

  for (var j = arr.length - 1; j >= 0; j--) {
    res.unshift(arr[j].map(item => item * product))
    product *= 10;
  }
  return res;
}
console.log(multiplyer([
  [2, 3],
  [3, 5]
]))

【讨论】:

    猜你喜欢
    • 2016-04-15
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    • 2011-12-07
    • 1970-01-01
    相关资源
    最近更新 更多