【问题标题】:Simplify code: height and width of an 2d-array简化代码:二维数组的高度和宽度
【发布时间】:2019-07-27 23:36:55
【问题描述】:

您好,我有一个问题,即如何获得二维数组的高度和宽度的简化代码没有功能所以我想出了这个。另外我需要比较这些数组的长度以查看它们是否相等,因此 [[true,false][true,false]] 有效但 [[true,false][true]] 无效

function size(bss) {
    let row_count = bss.length;
    let row_sizes = [];

    for (let i = 0; i < row_count; i++){
        row_sizes.push(bss[i].length)
    }

    if (Math.min.apply(null, row_sizes) === 0 || Math.min.apply(null, row_sizes) === Infinity){
        return "invalid";
    }
    return {"width":Math.min.apply(null, row_sizes), "height" : row_count };
}

输入:[[true,false][false,true]] 返回宽度:2 和高度:2 输入:[[true,false][true]] 返回“无效”

【问题讨论】:

  • "我会明白长度是没有功能的" - 听起来你是用.length() 而不是.length
  • 我做了bss[0].length 这确实给了我这个错误
  • 真的不清楚你的目标是什么。

标签: javascript multidimensional-array


【解决方案1】:

const valid1 = [ // valid elements
  [3, 2],
  [3, 2]
]
const invalid1 = [ // different sizes
  [1, 2],
  [1]
]
const valid2 = [ // only 1 element
  [1, 2]
]

function sizes(bss) {
  // avoid empty array (optional)
  if (!bss.length) {
    return 'invalid'
  }
  // is array same length with other elements
  const isEqualLength = bss.every(function(v) {
    return v.length === bss[bss.length - 1].length
  })
  if (isEqualLength) {
    // get minimal values from each array element
    const minBss = bss.map(function(v) {
      return Math.min.apply(null, v)
    })

    return {
      width: minBss[0],
      height: bss.length
    }
  }
  return 'invalid'
}

// check valid
console.log(sizes(valid1))
// check invalid length of elements of array
console.log(sizes(invalid1))
// check invalid length of array
console.log(sizes(valid2))

【讨论】:

    【解决方案2】:

    您可以通过使用map 而不是那个循环来简化,并将最小/最大值存储在一个变量中,这样您就不需要重复Math 调用。

    function size(bss) {
        const rowCount = bss.length;
        const rowSizes = bss.map(bs => bs.length);
        const minRow = Math.min(...rowSizes); // using spread syntax instead of apply()
        const maxRow = Math.max(...rowSizes);
    
        if (minRow != maxRow // ragged array
         || minRow === 0) // zero width
    //   || rowCount == 0 // same as minRow === Infinity - both already covered by first condition
            throw new Error("invalid 2d array");
        return {
            "width": minRow,
            "height": rowCount
        };
    }
    
    console.log(size([
        [true, false],
        [false, true]
    ])); // output: {"width": 2, "height": 2}
    
    
    console.log(size([
        [true, false],
        [false]
    ])); // throws an error "Uncaught Error: invalid 2d array"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-27
      • 2013-04-11
      • 1970-01-01
      • 2012-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-15
      相关资源
      最近更新 更多