我在使用下面的代码时遇到了问题,而且非常令人沮丧。问题似乎不是代码本身:程序可以很好地找到数组中的第二个最大和最小数字,但到目前为止只在labs.codeacademy.com JavaScript环境中这样做。
我去Coderbyte.org输入正确的代码来传递挑战。首先,每当我输入时," input.sort(函数(a,b){return(a-b);});"在coderbyte.org的网站上,由于某种原因,它会从页面中间缩进块的其余部分。这让我觉得它可能是我问题的根源。
当我将代码从codeacademy剪切并粘贴到coderbyte.org的网站时,它会粘贴精细缩进,但它只会返回一个空白框而不是第二个最高和最低值。我的问题:为什么它在一个网站上运行,而在另一个网站上运行?我已经坚持了两天了:有人请帮帮我吗?
function SecondGreatestLow(arr) {
input.sort(function(a,b){return (a-b);});
var input = arr;
var hashObject = {}
for (var i = input.length - 1; i >= 0; i--) {
var currentItem = input[i]; //WE LOOP THROUGH OUR NUMBER LIST
if (hashObject[currentItem] === true) {
input.splice(i, 1); //IF CURRENTITEM IS ALREADY IN HASHOBJECT, THEN DELETE THE COPY FOUND IN ARRAY AND MOVE ON TO NEXT NUMBER
}
hashObject[currentItem] = true; //IF CURRENTITEM IS NOT IN HASHOBJECT, ADD IT! THEN MOVE ON TO NEXT NUMBER.
}
//THE ARRAY HAS NOW BEEN "DE-DUPED":
//NEXT WE OUTPUT THE MAX AND MIN VALUES ACCORDING TO ARRAY SIZE
if (input.length >= 4) { //If 4+ chars, then remove the first two values to access the second by default
input.pop();
input.shift();
var min = Math.min.apply(null,input),
max = Math.max.apply(null,input);
return (max + " " + min);
} else {
var min2 = Math.min.apply(null,input),
max2 = Math.max.apply(null,input);
return max2 + " " + min2;
}
}
//example:
console.log(SecondGreatestLow(arr));
// THE OUTPUT ON CODEACADEMY IS AS FOLLOWS:
// arr = [ 1, 5, 10, 1, 25, 1, 5, 5, 5, 40, 5, 1, 100 ]; -> 40 5
// arr = [ 4, 90 ]; -> 90 4