确定哪个数组是更长的JavaScript

时间:2021-06-30 22:49:25

SORRY I HAD TO CHANGE THE QUESTION I SCREWED UP. The purpose is to use the Math.max function to determine the lengthiest array. I needed to add an additional parameter to make it practical because everyone was using > instead of Math.max. I was writing this example to fast and didn't think of that.

抱歉,我不得不改变我搞砸的问题。目的是使用Math.max函数来确定最长的数组。我需要添加一个额外的参数以使其实用,因为每个人都使用>而不是Math.max。我写的这个例子很快,没想到。

Is there an easier way to do this? The purpose is to be able to take many arguments (more than two) and find out which has a larger length. I'd like it to be dynamic, so It seems I need to give a name property to each array before passing them in. This is the only way to find an arrays name right?

有更简单的方法吗?目的是能够采用许多参数(超过两个)并找出哪个具有更大的长度。我希望它是动态的,所以我似乎需要在传递它们之前为每个数组赋予一个name属性。这是找到数组名称的唯一方法吗?

var arrayLogA = [8, 7, 5, 4, 6, 8, 0, 9, 4];
arrayLogA.name = 'arrayLogA';

var arrayLogB = [1, 5, 4, 6, 5, 9, 3, 2, 7, 3, 2]
arrayLogB.name = 'arrayLogB';

var arrayLogC = [1, 6, 9, 3, 3, 7, 3, 2]
arrayLogC.name = 'arrayLogC';

function returnLargestArray(a, b, C) {

    ...
}

returnLargestArray(arrayLogA, arrayLogB);

ok, this is more practical, if I'm going to explain the Math.max function and also return the largest, I'm going to have to rethink the function. Sorry for any confusion. I typically write good questions but I think I rushed this one. Very sorry.

好吧,这更实用,如果我要解释Math.max函数并返回最大值,我将不得不重新考虑该函数。对不起任何困惑。我通常写好问题,但我想我赶紧过这个问题。很抱歉。

I may need to pass additional parameters in. SO maybe I should not have used a, b, c as the arguments.

我可能需要传递其他参数。所以我可能不应该使用a,b,c作为参数。

7 个解决方案

#1


1  

Alright, this might be a little less than ideal, and certainly feels a bit weird, but you could do something like this.

好吧,这可能不太理想,当然感觉有点奇怪,但你可以做这样的事情。

var arrayLogA = [8, 7, 5, 4, 6, 8, 0, 9, 4];
arrayLogA.name = 'arrayLogA';

var arrayLogB = [1, 5, 4, 6, 5, 9, 3, 2, 7, 3, 2];
arrayLogB.name = 'arrayLogB';

var arrayLogC = [1, 6, 9, 3, 3, 7, 3, 2];
arrayLogC.name = 'arrayLogC';
...

var arrayLogN = [ ... ];
arrayLogN.name = 'arrayLogN';

function returnLargestArray(/* some unknown number of arrays */) {
  var lengths = [];

  // store lengths of each array
  for(var i = 0; i < arguments.length; i++){
    lengths.push(arguments[i].length);
  }

  // use Math.max to get biggest length
  var largest = Math.max.apply(null, lengths);

  // use indexOf to get the index of biggest length
  var indexOfLargest = lengths.indexOf(largest);

  // use the indexOfLargest to return that value from arguments
  return arguments[indexOfLargest].name;
}

returnLargestArray(arrayLogA, arrayLogB, arrayLogC, ..., arrayLogN);

Using this method will return to you the lengthiest array passed in to the function, without requiring you to name each array.

使用此方法将返回传递给函数的最长数组,而无需为每个数组命名。

Just a quick note: this function invokes Math.max.apply rather than just Math.max because Math.max expects a number of inputs, rather than just one array that we're trying to find the maximum within. To make Math.max work on an array, we have to use Math.max.apply.

快速说明:此函数调用Math.max.apply而不仅仅是Math.max,因为Math.max需要大量输入,而不仅仅是我们试图在其中找到最大值的一个数组。要使Math.max适用于数组,我们必须使用Math.max.apply。

I hope this does what you want!

我希望这能做到你想要的!

Edit: Added name properties to the arrays in order to return name at end of function.

编辑:为数组添加名称属性,以便在函数结束时返回名称。

#2


2  

function returnLargestArray(a,b){
  if(!a || typeof a.length =="undefined" ||
     !b || typeof b.length =="undefined") {return;}
  if(a.length==b.length){/*return some value of your choosing*/}
  return a.length>b.length?a:b;
}
returnLargestArray([1,2,3],[1,2,3,4]);

But beware of caveats for non "simple" arrays.

但要注意非“简单”数组的警告。

  • Non-array objects with a length property
  • 具有length属性的非数组对象
  • Arrays which have had indexes explicitly set, will be counted based on their max index, not the number of "used" indexes
  • 已明确设置索引的数组将根据其最大索引计算,而不是“已使用”索引的数量

#3


1  

Try this. (I haven't tested it yet, but it makes sense!)

尝试这个。 (我还没有测试过,但它有意义!)

function returnLargestArray(a, b) {

    if (a.length > b.length) {
        return console.log("winner: "+ a.name);
    } else {
        return console.log("winner: "+ b.name);
    }
}

If they're the same length that will fail, but you get the idea.

如果它们的长度相同会失败,但你会明白这一点。

#4


1  

What about something like:

怎么样的:

if (a.length > b.length) {
  console.log("winner: "+ a.name);
  return a;
else {
  console.log("winner: "+ b.name);
  return b;
}

or if you want it to be really short:

或者如果你想要它真的很短:

return a.length > b.length ? a : b;

As a side note, your logic could use a little work. Right now it returns the output from console.log, which is undefined. Returning the array makes more sense, and makes more sense from the name of your function.

作为旁注,你的逻辑可以使用一点点工作。现在它返回console.log的输出,这是未定义的。返回数组更有意义,并且从函数名称更有意义。

#5


1  

function returnLargestArray(a, b) {
    return 'winner is ' + (a.length == b.length ? 'nobody' : (a.length > b.length ? a : b).name);
}

#6


1  

You could use a different structure in your code. Looks like you need objects with two properties: A name and an array of data.

您可以在代码中使用不同的结构。看起来您需要具有两个属性的对象:名称和数据数组。

var logA = {
  name: "logA",
  array: [8, 7, 5, 4, 6, 8, 0, 9, 4]
};

var logB = {
  name: "logB",
  array: [1, 5, 4, 6, 5, 9, 3, 2, 7, 3, 2]
};

Then define a function operating on such objects:

然后定义对这些对象进行操作的函数:

function largestLog( a, b ) {
    if ( a.array.length > b.array.length ) {
       return a;
    }
    else {
       return b;
    }
}

And then you can call the function, get the object with largest array, and print its name to console:

然后你可以调用函数,获取具有最大数组的对象,并将其名称打印到控制台:

var l = largestLog( logA, logB );
console.log( l.name );

#7


1  

In normal circumstances you would probably check the length of the arrays and then return the one that satisfied the logic (larger or smaller) then work with that object.

在正常情况下,您可能会检查数组的长度,然后返回满足逻辑(更大或更小)的数组,然后使用该对象。

The reassignment of a and b, to arrayA and arrayB seems to have no merit, other that to give a semantic answer. You may as well use those var assignments as strings as it would make more sense in the context your are demonstrating.

将a和b重新分配给arrayA和arrayB似乎没有任何价值,除了给出语义答案。您也可以将这些var赋值用作字符串,因为它在您演示的上下文中更有意义。

var arrayLogA = [8, 7, 5, 4, 6, 8, 0, 9, 4];
var arrayLogB = [1, 5, 4, 6, 5, 9, 3, 2, 7, 3, 2]
function returnLargestArray(a, b) {
    var a = a.length,
        b = b.length,
        winner = 'arrayA';
    if(a < b && a !== b) {
        winner = 'arrayB';
    } else {
      winner = 'none';
    }
    return winner;
}
returnLargestArray(arrayLogA, arrayLogB);

Math.max() is probably surplus to requirements, I wouldn't imagine it has any speed advantages over normal operators [=!<>] seeing as you are bringing another object in to play Math and accessing a function of that object.

Math.max()可能是对需求的过剩,我不认为它比普通的运算符[=!<>]有任何速度优势,因为你正在使用另一个对象来播放Math并访问该对象的一个​​函数。

The way I have been taught is (in this binary scenario [true, false] [a or b] etc) is to set a return value at the top of the function. This way everyone who reads can easily see what the functions purpose is, then use your logic to switch that state.

我被教导的方式是(在这个二进制场景[true,false] [a或b]等)是在函数顶部设置一个返回值。这样,每个阅读的人都可以轻松地看到功能的用途,然后使用逻辑来切换该状态。

So if winner = a; you test is b larger than a, if it is, set winner = b. Saves a lot of code and should be more efficient.

如果胜利者= a;你测试的是b大于a,如果是,则设置winner = b。节省了大量代码,应该更有效率。

#1


1  

Alright, this might be a little less than ideal, and certainly feels a bit weird, but you could do something like this.

好吧,这可能不太理想,当然感觉有点奇怪,但你可以做这样的事情。

var arrayLogA = [8, 7, 5, 4, 6, 8, 0, 9, 4];
arrayLogA.name = 'arrayLogA';

var arrayLogB = [1, 5, 4, 6, 5, 9, 3, 2, 7, 3, 2];
arrayLogB.name = 'arrayLogB';

var arrayLogC = [1, 6, 9, 3, 3, 7, 3, 2];
arrayLogC.name = 'arrayLogC';
...

var arrayLogN = [ ... ];
arrayLogN.name = 'arrayLogN';

function returnLargestArray(/* some unknown number of arrays */) {
  var lengths = [];

  // store lengths of each array
  for(var i = 0; i < arguments.length; i++){
    lengths.push(arguments[i].length);
  }

  // use Math.max to get biggest length
  var largest = Math.max.apply(null, lengths);

  // use indexOf to get the index of biggest length
  var indexOfLargest = lengths.indexOf(largest);

  // use the indexOfLargest to return that value from arguments
  return arguments[indexOfLargest].name;
}

returnLargestArray(arrayLogA, arrayLogB, arrayLogC, ..., arrayLogN);

Using this method will return to you the lengthiest array passed in to the function, without requiring you to name each array.

使用此方法将返回传递给函数的最长数组,而无需为每个数组命名。

Just a quick note: this function invokes Math.max.apply rather than just Math.max because Math.max expects a number of inputs, rather than just one array that we're trying to find the maximum within. To make Math.max work on an array, we have to use Math.max.apply.

快速说明:此函数调用Math.max.apply而不仅仅是Math.max,因为Math.max需要大量输入,而不仅仅是我们试图在其中找到最大值的一个数组。要使Math.max适用于数组,我们必须使用Math.max.apply。

I hope this does what you want!

我希望这能做到你想要的!

Edit: Added name properties to the arrays in order to return name at end of function.

编辑:为数组添加名称属性,以便在函数结束时返回名称。

#2


2  

function returnLargestArray(a,b){
  if(!a || typeof a.length =="undefined" ||
     !b || typeof b.length =="undefined") {return;}
  if(a.length==b.length){/*return some value of your choosing*/}
  return a.length>b.length?a:b;
}
returnLargestArray([1,2,3],[1,2,3,4]);

But beware of caveats for non "simple" arrays.

但要注意非“简单”数组的警告。

  • Non-array objects with a length property
  • 具有length属性的非数组对象
  • Arrays which have had indexes explicitly set, will be counted based on their max index, not the number of "used" indexes
  • 已明确设置索引的数组将根据其最大索引计算,而不是“已使用”索引的数量

#3


1  

Try this. (I haven't tested it yet, but it makes sense!)

尝试这个。 (我还没有测试过,但它有意义!)

function returnLargestArray(a, b) {

    if (a.length > b.length) {
        return console.log("winner: "+ a.name);
    } else {
        return console.log("winner: "+ b.name);
    }
}

If they're the same length that will fail, but you get the idea.

如果它们的长度相同会失败,但你会明白这一点。

#4


1  

What about something like:

怎么样的:

if (a.length > b.length) {
  console.log("winner: "+ a.name);
  return a;
else {
  console.log("winner: "+ b.name);
  return b;
}

or if you want it to be really short:

或者如果你想要它真的很短:

return a.length > b.length ? a : b;

As a side note, your logic could use a little work. Right now it returns the output from console.log, which is undefined. Returning the array makes more sense, and makes more sense from the name of your function.

作为旁注,你的逻辑可以使用一点点工作。现在它返回console.log的输出,这是未定义的。返回数组更有意义,并且从函数名称更有意义。

#5


1  

function returnLargestArray(a, b) {
    return 'winner is ' + (a.length == b.length ? 'nobody' : (a.length > b.length ? a : b).name);
}

#6


1  

You could use a different structure in your code. Looks like you need objects with two properties: A name and an array of data.

您可以在代码中使用不同的结构。看起来您需要具有两个属性的对象:名称和数据数组。

var logA = {
  name: "logA",
  array: [8, 7, 5, 4, 6, 8, 0, 9, 4]
};

var logB = {
  name: "logB",
  array: [1, 5, 4, 6, 5, 9, 3, 2, 7, 3, 2]
};

Then define a function operating on such objects:

然后定义对这些对象进行操作的函数:

function largestLog( a, b ) {
    if ( a.array.length > b.array.length ) {
       return a;
    }
    else {
       return b;
    }
}

And then you can call the function, get the object with largest array, and print its name to console:

然后你可以调用函数,获取具有最大数组的对象,并将其名称打印到控制台:

var l = largestLog( logA, logB );
console.log( l.name );

#7


1  

In normal circumstances you would probably check the length of the arrays and then return the one that satisfied the logic (larger or smaller) then work with that object.

在正常情况下,您可能会检查数组的长度,然后返回满足逻辑(更大或更小)的数组,然后使用该对象。

The reassignment of a and b, to arrayA and arrayB seems to have no merit, other that to give a semantic answer. You may as well use those var assignments as strings as it would make more sense in the context your are demonstrating.

将a和b重新分配给arrayA和arrayB似乎没有任何价值,除了给出语义答案。您也可以将这些var赋值用作字符串,因为它在您演示的上下文中更有意义。

var arrayLogA = [8, 7, 5, 4, 6, 8, 0, 9, 4];
var arrayLogB = [1, 5, 4, 6, 5, 9, 3, 2, 7, 3, 2]
function returnLargestArray(a, b) {
    var a = a.length,
        b = b.length,
        winner = 'arrayA';
    if(a < b && a !== b) {
        winner = 'arrayB';
    } else {
      winner = 'none';
    }
    return winner;
}
returnLargestArray(arrayLogA, arrayLogB);

Math.max() is probably surplus to requirements, I wouldn't imagine it has any speed advantages over normal operators [=!<>] seeing as you are bringing another object in to play Math and accessing a function of that object.

Math.max()可能是对需求的过剩,我不认为它比普通的运算符[=!<>]有任何速度优势,因为你正在使用另一个对象来播放Math并访问该对象的一个​​函数。

The way I have been taught is (in this binary scenario [true, false] [a or b] etc) is to set a return value at the top of the function. This way everyone who reads can easily see what the functions purpose is, then use your logic to switch that state.

我被教导的方式是(在这个二进制场景[true,false] [a或b]等)是在函数顶部设置一个返回值。这样,每个阅读的人都可以轻松地看到功能的用途,然后使用逻辑来切换该状态。

So if winner = a; you test is b larger than a, if it is, set winner = b. Saves a lot of code and should be more efficient.

如果胜利者= a;你测试的是b大于a,如果是,则设置winner = b。节省了大量代码,应该更有效率。