duanmu1736 2013-01-09 23:27
浏览 23
已采纳

javascript相当于数组的php max

I have a function in php that selects the array with that contains the most elements.

$firstArray = array('firstArray','blah','blah','blah');
$secondArray = array('secondArray','blah','blah');
$thirdArray = array('thirdArray','blah','blah','blah','blah');

then I get the name of the variable with the highest length like this:

$highest = max($firstArray, $secondArray, $thirdArray)[0];

but I am developing an application and I want to avoid using php and I have tried javascript's Math.max() to achieve the same results but it doesn't work the same way unless I do

Math.max(firstArray.length, secondArray.length, thirdArray.length)

But this is useless since I need to know the name of the array that contains the most elements. Is there any other way to achieve this?

  • 写回答

3条回答 默认 最新

  • drj58429 2013-01-09 23:30
    关注

    This function takes as input an array of arrays, and returns the largest one.

    function largestArray(arrays){
       var largest;
       for(var i = 0; i < arrays.length; i++){
           if(!largest || arrays[i].length > largest.length){
              largest = arrays[i];
           }
       }
       return largest;
    }
    

    We can test it out with your example:

    firstArray = ['firstArray','blah','blah','blah'];
    secondArray = ['secondArray','blah','blah'];
    thirdArray = ['thirdArray','blah','blah','blah','blah'];
    
    // should print the third array
    console.log(largestArray([firstArray, secondArray, thirdArray]));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了