我正在执行代码挑战,并且尝试将排序数组中的每个数字与另一个数字进行比较,因为它们不匹配。我无法完成此挑战,因为即使我的控制台日志在for循环中使用它之前正确打印了排序后的数组,但一旦在for循环中使用它,该数组似乎仍保留其原始(未排序)顺序。这是代码:

function minMinMax(array) {
    let minAbsent = 0
    // sort the array from smallest to largest
    let smallestToLargest = array.sort((a, b) => a - b)
    console.log(smallestToLargest)
    const smallest = smallestToLargest[0]
    // sort the array from largest to smallest
    let largestToSmallest = array.sort((a, b) => b - a)
    const largest = largestToSmallest[0]
    // use second smallest number as starting point for loop, then after each number check
    // to see if that number is in the array, if not then add the value to our array
    for (i = 1, j = smallestToLargest[1]; i < smallestToLargest.length; i++, j++) {
      if (j !== smallestToLargest[i]) {
        minAbsent = j
        }
        console.log(smallestToLargest[i])
        console.log('this is the min absent ' + minAbsent)
      }
    return [smallest, minAbsent, largest]
  }


当第二个console.log打印时,它会读回给定的数组(具有原始的数字顺序,而不是排序的数组)。那有什么呢?

最佳答案

似乎出现的问题是,尽管您具有三个单独的指针“数组”,“ smallestToLargest”和“ largestToSmallest”,但它们都引用了相同的实际数组对象。 “ array.sort(...)”对调用该方法的数组进行排序,并返回对该数组的引用。

如果您在创建maximumToSmallest之后尝试将smallestToLargest记录到控制台,您会看到smallestToLargest将以降序打印-因为在调用第二个array.sort时它将按降序排序。

let smallestToLargest = array.sort((a, b) => a - b)
console.log(smallestToLargest);
const smallest = smallestToLargest[0]
// sort the array from largest to smallest
let largestToSmallest = array.sort((a, b) => b - a)
console.log(smallestToLargest);


在随机数组上进行测试,得出:

[1, 3, 14, 29, 311, 323]
[323, 311, 29, 14, 3, 1]


要保留“ smallestToLargest”数组,可以使用“ slice(0)”对其进行克隆。

尝试这个:

function minMinMax(array) {
    let minAbsent = 0
    // sort the array from smallest to largest
    let smallestToLargest = array.sort((a, b) => a - b).slice(0);
    console.log(smallestToLargest);
    const smallest = smallestToLargest[0]
    // sort the array from largest to smallest
    let largestToSmallest = array.sort((a, b) => b - a).slice(0);
    console.log(smallestToLargest);
    const largest = largestToSmallest[0]
    // use second smallest number as starting point for loop, then after each number check
    // to see if that number is in the array, if not then add the value to our array
    for (i = 1, j = smallestToLargest[1]; i < smallestToLargest.length; i++, j = smallestToLargest[i]) {
      if (j !== smallestToLargest[i]) {
        minAbsent = j
        }
        console.log(smallestToLargest[i])
        console.log('this is the min absent ' + minAbsent)
      }
  console.log(smallestToLargest);
    return [smallest, minAbsent, largest]
  };

09-17 18:52