Javascript 具有相等值的数组上的Math.max方法
我正在处理一些coderbyte代码,注意到当我尝试获取一个相等值数组中的max项时,会返回Javascript 具有相等值的数组上的Math.max方法,javascript,arrays,math,Javascript,Arrays,Math,我正在处理一些coderbyte代码,注意到当我尝试获取一个相等值数组中的max项时,会返回undefined。记录时,最小值为logs80,而不是undefined。为什么会这样 更新代码: function noRepeat(arr) { tmp = [] if (arr.length === 2 && arr[0] === arr[1]) { return arr; } for (var i = 0;i<arr.leng
undefined
。记录时,最小值为logs80
,而不是undefined
。为什么会这样
更新代码:
function noRepeat(arr) {
tmp = []
if (arr.length === 2 && arr[0] === arr[1]) {
return arr;
}
for (var i = 0;i<arr.length;i++) {
if (tmp.indexOf(arr[i]) === -1) {
tmp.push(arr[i])
}
}
return tmp
}
function SecondGreatLow(arr) {
arr = noRepeat(arr).sort(function (a,b) {return a-b;});
var low = arr[arr.indexOf(Math.min.apply(Math,arr))+1];
console.log("low",low);
var high = arr[arr.indexOf(Math.max.apply(Math,arr))-1];
console.log("high",high);
return low +" "+high;
}
console.log(SecondGreatLow([80,80]));
事实上,这很好。您想如何在两个类似的数字数组中找到第二个最大\最小的数字? 它应该输出“无解决方案”或其他内容。就像没有空数组的解决方案一样
function SecondGreatLow(arr)
{
arr = noRepeat(arr).sort(function (a,b) {return a-b;});
if (arr.length < 2)
return "No solution";
console.log("low ", arr[1]);
console.log("high ", arr[arr.length - 2]);
return low + " " + high;
}
例如,您有一个数组[1,1,2]。删除重复并得到[1,2]。
现在,您的算法返回low=arr[1]=2和high=arr[2-2]=arr[0]=1。
答案是正确的-2是第二个最小值,1是第二个最大值。Ahhh我在发布后立即发现了这一点。。。所以max方法是有效的。它返回80的第一个实例。当它试图从索引0中减去1时,结果未定义,因为没有值。:)确切地为什么要尝试获取下一项\上一项?arr已排序,为什么不使用arr[0]和arr[arr.length-1]获取低/高?问题集如下:使用函数SecondGreatLow(arr)取存储在arr中的数字数组,分别返回第二低和第二高的数字,用空格分隔。例如:如果arr包含[7,7,12,98,106],则输出应为12 98。数组将不为空,并且至少包含2个数字。如果只有两个数字,这可能会变得棘手!知道了。这是有道理的。我忘了补充一点,有时候数组可能是两个不同的值。因此,如果它是[12,39],我需要if语句“if(arr.length==2&&arr[0]==arr[1]),它才能按预期工作。谢谢你的帮助。
function SecondGreatLow(arr)
{
arr = noRepeat(arr).sort(function (a,b) {return a-b;});
if (arr.length < 2)
return "No solution";
console.log("low ", arr[1]);
console.log("high ", arr[arr.length - 2]);
return low + " " + high;
}
if (arr.length === 2)
{
return arr[1] + " " + arr[0];
}