获取 JavaScript 数组元素的最大长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6043471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:15:53  来源:igfitidea点击:

get maximum length of JavaScript array element

javascriptjqueryarrays

提问by Paul Jones

If I have the following array :

如果我有以下数组:

array = ['a', 'abcde', 'ab'] ;

I would like to get the maximum length of the array elements ie 5 (for the element 'abcde').

我想获得数组元素的最大长度,即 5(对于元素“abcde”)。

I know that you can get the length of an array element via (eg) array[1].length but I don't know how to get the maximum length.

我知道你可以通过 (eg) array[1].length 获得数组元素的长度,但我不知道如何获得最大长度。

Any answer in JavaScript or jQuery would be great.

JavaScript 或 jQuery 中的任何答案都会很棒。

TIA

TIA

Paul Jones

保罗·琼斯

回答by Andy E

One-liner for you:

为您准备的单线:

 Math.max.apply(Math, $.map(array, function (el) { return el.length }));

Working example: http://jsfiddle.net/5SDBx/

工作示例:http: //jsfiddle.net/5SDBx/

You can do it without jQuery in newer browsers (or even older browsers with a compatibility implementationof Array.prototype.map) too:

您也可以在较新的浏览器(甚至具有兼容性实现的较旧浏览器)中不用 jQuery 来实现Array.prototype.map

Math.max.apply(Math, array.map(function (el) { return el.length }));

回答by James

One (possibly rubbish) way of doing that, without using Jquery:

不使用 Jquery 的一种(可能是垃圾)方法:

var myarray = ['a','abcde','ab'];
var maxlen = 0;
for (i=0; i<myarray.length; i++) {
  if (myarray[i].length>maxlen) {
    maxlen = myarray[i].length;
  }
}

回答by Dávid Veszelovszki

A new answer to an old question: in ES6 you can do even shorter:

一个老问题的新答案:在 ES6 中,你可以做得更短:

Math.max(...array.map(el => el.length));

回答by Mr. Polywhirl

By using Array.prototype.reduce(), you can elegantly perform a Math.max()calculation for each item in the array. It does not matter whether the items in the array are string or sub-arrays (2D array, matrix, etc.), this will work because Stringand Arrayboth have a prototype.length()function.

通过使用Array.prototype.reduce(),您可以优雅地Math.max()为数组中的每个项目执行计算。不要紧数组中的物品是否串或子阵列(2D阵列,矩阵,等),这将工作,因为StringArray两者都具有prototype.length()功能。

I also added a check for integer values per your commentabove.

我还根据上面的评论添加了对整数值的检查。

function arrayItemMax(arr) {
    return arr.reduce(function (result, val) {
        return Math.max(result, !isNaN(val) ? parseInt(val) : val.length);
    }, 0);
}

function print(text) {
  document.getElementsByTagName('body')[0].innerHTML += text + '<br />';
}

print(arrayItemMax(['a', 'abcde', 'ab'])); // 5
print(arrayItemMax([1, 5, 2]));            // 5
print(arrayItemMax(['1', '5', '2']));      // 5

One liner:

一个班轮:

function(a){return a.reduce(function(r,v){return Math.max(r,!isNaN(v)?parseInt(v):v.length);},0);}

回答by alex

You could use jQuery's each()to iterate a little nicer.

您可以使用 jQueryeach()来更好地迭代。

var maxLength = 0;

$.each(array, function(i, item) {
   maxLength = Math.max(maxLength, item.length);
});

Or plain ol' JavaScript...

或者普通的 ol' JavaScript ...

var maxLength = 0;

for (var i = 0, length = array.length; i < length; i++) {
   maxLength = Math.max(maxLength, array[i].length);
};

回答by Patrick

There are several ways to do that.

有几种方法可以做到这一点。

I would iterate through all the array elements and store the longest element in a local variable. You get the longest element by comparing the first array element with the second, then storing the longer one. Then go on and compare each element with the longest one so far.

我会遍历所有数组元素并将最长的元素存储在局部变量中。通过将第一个数组元素与第二个元素进行比较,您可以获得最长的元素,然后存储较长的元素。然后继续将每个元素与迄今为止最长的元素进行比较。

You just need one loop to do that.

你只需要一个循环就可以做到这一点。

回答by Manvel

In such cases, there is a very useful function. Array.reduce

在这种情况下,有一个非常有用的功能。 Array.reduce

['a', 'abcde', 'ab'].reduce((r,s) => r.length > s.length ? r : s, 0);

回答by avalkab

You can create own your code. Follow this ->

您可以创建自己的代码。按照这个 ->

Array.prototype.count = function(){  return this.length; }

then use

然后使用

arr = [ "erhan",1,"sonmez",2 ];
arrCount = arr.count();