let descend = Object.assign([],array);
上面的行不会通过引用复制数组。
function minMinMax(array) {
let minAbsent = 0;
let descend = Object.assign([],array);
// 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 = descend.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]
}
我认为这样会很好。
,
问题似乎是,尽管您有三个单独的指针“数组”,“ smallestToLargest”和“ largestToSmallest”,但它们都引用了相同的实际数组对象。 “ array.sort(...)”对调用方法的数组进行排序,并返回对该数组的引用。
如果在创建largestToSmallest之后尝试将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,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[i]) {
if (j !== smallestToLargest[i]) {
minAbsent = j
}
console.log(smallestToLargest[i])
console.log('this is the min absent ' + minAbsent)
}
console.log(smallestToLargest);
return [smallest,largest]
};
本文链接:https://www.f2er.com/3115807.html