如何声明一个空的NUMERIC变量? (相当于Java中的“ int x;”)

时间:2019-09-30 09:32:39

标签: javascript

给定一个带有子数组的数组,我需要返回一个由最大数量的子数组组成的新数组。

数组:

let arr = [[1,2], [10, 15], [30, 40], [-1, -50]];


新数组应为:

newArr = [2, 40, -1];


我已经解决了这个问题,但是它对于负数不起作用,因为初始值为0。
如何声明一个空的数字变量,例如“ int x;”。在java中?

  let newArr = [0, 0, 0, 0]; // Instead of 0 I need an empty numeric 
  for (let x = 0; x < arr.length; x++) {
    for (let y = 0; y < arr[x].length; y++) {
      if (newArr[x] < arr[x][y]) {
        newArr[x] = arr[x][y];
      }
    }
  }

console.log(newArr) // 2,15,40,0

预期:2、15、40,-1

4 个答案:

答案 0 :(得分:3)

您可以拿Math.max来散布物品。

let array = [[1,2], [10, 15], [30, 40], [-1, -50]],
    max = array.map(a => Math.max(...a));

console.log(max);

答案 1 :(得分:2)

您的问题是-1不小于0,因此不会更新您的数组,而是用newArr而不是{ {1}},这样任何数字都将大于这样的数字:

-Infinity

答案 2 :(得分:1)

空数值对您使用逻辑都无济于事,因为您设置了错误的初始值进行比较。看到与您相同的内容,并进行了较小的修复:

let arr = [[1,2], [10, 15], [30, 40], [-1, -50]];

 let newArr = [arr[0][0], arr[1][0], arr[2][0], arr[3][0]]; 
  for (let x = 0; x < arr.length; x++) {
    for (let y = 0; y < arr[x].length; y++) {
      if (newArr[x] < arr[x][y]) {
        newArr[x] = arr[x][y];
      }
    }
  }

答案 3 :(得分:1)

您可以将初始值用作第一个元素或子数组。

  
  let arr = [[1,2], [10, 15], [30, 40], [-1, -50]];

  newArr = [] // Instead of 0 I need an empty numeric
  for (let x = 0; x < arr.length; x++) {
	newArr[x] = arr[x][0]
    for (let y = 0; y < arr[x].length; y++) {
      if (newArr[x] < arr[x][y]) {
        newArr[x] = arr[x][y];
      }
    }
  }

console.log(newArr) // 2,15,40,0

或者您可以使用map函数返回最大值。

let arr = [[1,2], [10, 15], [30, 40], [-1, -50]];

let newArr = arr.map(subArr => Math.max(...subArr))

console.log(newArr)