简体   繁体   English

相同的代码在不同的设备上运行不同

[英]Same code runs differently on different devices

I'm new to coding, still learning. 我是编码的新手,还在学习。 My friend gave me a task to write a function that does return the 2nd highest number from an array, I've managed to do it using array.prototype.sort(). 我的朋友给了我一个任务来编写一个从数组中返回第二高数字的函数,我已经设法使用array.prototype.sort()。 He said to replace "-" with a "<" or ">" to make the code more clear, that's where the problem started. 他说要用“<”或“>”替换“ - ”以使代码更清晰,这就是问题的起点。

I'm using VCS on windows, and it's not working properly. 我在Windows上使用VCS,但它无法正常工作。 My friend uses a mac, everything works fine. 我的朋友使用mac,一切正常。 Tried it on jsfiddle, everything works fine. 在jsfiddle上尝试过,一切正常。

const secondMax = (arr) => {
  return arr.sort((a, b) => b - a)[1]; //does return the correct number after console.log()
};
const secondMax = (arr) => {
  return arr.sort((a, b) => a < b)[1]; //does not
};

"a < b" should be sorting descending "a > b" should be sorting ascending But no matter which operator I use, the sorting fails and just returns the second number from the array “a <b”应该排序降序“a> b”应该按升序排序但是无论我使用哪个运算符,排序都会失败,只返回数组中的第二个数字

You're supposed to return a number, not a boolean. 你应该返回一个数字,而不是一个布尔值。 So the first is correct. 所以第一个是正确的。 The latter might work by chance on some javascript engines, but it's not guaranteed to. 后者可能会在某些javascript引擎上偶然发挥作用,但并不能保证。

sort sorts the array as String by default. sort默认将数组sortString If you pass a comparator, then it's a function which will depend on two parameters and return : 如果你传递一个比较器,那么它是一个依赖于两个参数并returnfunction

  • negative, if the first parameter is smaller than the second 如果第一个参数小于第二个参数,则为负数
  • 0 if they are equal 0如果他们是平等的
  • positive, if the first parameter is greater than the second 如果第一个参数大于第二个参数,则为正数

Using a logical operator instead of the above is mistaken. 使用逻辑运算符而不是上述错误是错误的。

However, if you are interested in finding the second largest number, then it's better to do it using a cycle: 但是,如果您有兴趣找到第二大数字,那么最好使用一个循环:

var largestNumbers = [];
var firstIndex = (arr[0] < arr[1]) ? 1 : 0;
largestNumbers.push(arr[firstIndex]);
largestNumbers.push(arr[1 - firstIndex]);
for (var i = 2; i < arr.length; i++) {
    if (largestNumbers[1] < arr[i]) {
        if (largestNumbers[0] < arr[i]) {
            largestNumbers[1] = largestNumbers[0];
            largestNumbers[0] = arr[i];
        }
    }
}

This is quicker than sorting an array and more importantly, it does not destroy your initial order just to find the second largest number. 这比排序数组更快,更重要的是,它不会破坏您的初始订单只是为了找到第二大数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM