【问题标题】:Fill an array the right way and get the maximum out of it以正确的方式填充数组并从中获得最大值
【发布时间】:2017-06-28 15:11:40
【问题描述】:

我对 Javascript 非常陌生,我很难找到解决方案。 我有一个名为pat 的动态变化数组。数组的元素具有坐标 x 和 y。 所以现在,我想使用一个循环将所有元素的所有 x 值存储到一个名为 newArray 的新数组中。然后在填写newArray 之后,我希望从中获得最大值。问题是,我目前很难以正确的方式使用 push 函数。我的代码如下。希望,有人可以帮忙。谢谢各位!

for ( i = 0; i < pat.length; i++ ) {
    console.log(pat[i].x);
    var newArray = pat.push[i];
    console.log(newArray);
};

【问题讨论】:

    标签: javascript arrays loops push


    【解决方案1】:

    像这样使用push

    var newArray = []; // create an empty array
    
    for (var i = 0; i < pat.length; i++) {
      newArray.push(pat[i].x); // push the x value of the current element to the array
    };
    
    var max = Math.max.apply(null, newArray); // calculate the maximum of all x values
    

    使用map 的更实用的方法是:

    var newArray = pat.map(obj => obj.x);
    var max = Math.max.apply(null, newArray);
    

    PS:你确定要调用数组newArray吗?

    编辑:我计算最大值的解决方案如下:Math.max 返回其所有参数的最大值。 apply 以数组元素作为参数调用 Math.max

    【讨论】:

      【解决方案2】:

      您应该在 for 循环之外声明数组,否则它将在每次迭代时重新声明。您可以使用 array literal syntax var arrayName = []; 声明数组。要将元素添加到数组中,您应该使用 arrayName.push(value) 方法。要找到数组中的最大数,我们必须使用Math,这是一个内置对象,具有数学常数和函数的属性和方法。 我们只需要来自这些对象的max 方法,它以数字作为参数,从中返回最大的Math.max(a, b, c, d ...),而它只需要我们不能将Array 作为参数传递给它的数字,这样做我们可以使用来自Function.prototype.apply(apply 方法)它调用具有给定此值的函数,并将参数作为数组(或类似数组的对象)提供。 这就是我们如何将数组作为参数传递给Math.max.apply(thisArg, [argumentsAsArray]);Math.max.apply(null, newArray);

      var newArray = []; // create an empty array outside the for loop
      for ( i = 0; i < pat.length; i++ ){
         newArray.push(pat[i].x); // add new element to the array
      }
      
      console.log(newArray);
      
      var max = Math.max.apply(null, newArray); // take biggest number from the array
      console.log(max);
      

      【讨论】:

      • 虽然这是我对问题的回答,但仅代码的答案是不受欢迎的。还请向 OP 提供解释以解释您的答案。 How to Answer
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-14
      • 2021-05-17
      相关资源
      最近更新 更多