gpt4 book ai didi

javascript - 为什么 "Array.prototype.slice(arguments)"给我一个空的 "[]"?

转载 作者:行者123 更新时间:2023-12-02 23:01:57 27 4
gpt4 key购买 nike

我编写了一个函数getMax,它模拟Math.max,可以从一组数字中获取最大数字。该函数接受可变参数。

  1. 我使用Array.prototype.slice(arguments)将它们转换为真正的数组。但我失败了,我得到一个空数组[]。如果我使用 Array.from(arguments) 我将得到一个正确的数组。我不知道为什么 Array.prototype.slice(arguments) 的传统方式对我不起作用。

  2. 此函数的另一个问题是,在我获得正确的参数数组后,getMax 的返回值为 undefined,但我确实得到了 filterMax 函数中的返回值 7 让我很困惑。

function getMax() {
"use strict";

let filterMax = function(arr) {
let maxValue = arr[0];
let resultArr = arr.filter(function(value) {
return value > maxValue;
});
if (resultArr.length == 0) {
return maxValue; //output: 7
} else {
resultArr = filterMax(resultArr);
}
};

let args = Array.from(arguments); //output: [ 3, 7, 2, 5, 1, 4 ]
// let args = Array.prototype.slice(arguments); //output: []

console.log(args); //output: []

return filterMax(args); //output: undefined
}

console.log(getMax(3, 7, 2, 5, 1, 4)); //output: undefined

最佳答案

 Array.prototype.slice(arguments)

基本相同

 [].slice(arguments)

(除了第一种情况下 thisArray.prototype,但这或多或少等于在空数组上调用它)

... 返回一个空数组,因为从空数组进行切片将始终导致空数组。您可能想做:

 Array.prototype.slice.call(arguments)

调用 .slicethisarguments ,因此它会产生所需的数组,但我更喜欢 Array.from(arguments)[...arguments] ,或者更好的是,一个剩余参数:

function findMax(...numbers) {
//...
}

Another problem with this function is that after I get a correct arguments array, the return value of getMax is undefined, but I do get a return value 7 in filterMax function which confuses me

嗯,那是因为:

let maxValue = arr[0];
let resultArr = arr.filter(function(value) {
return value > maxValue;
});

过滤掉大于第一个数组元素的任何数组元素(在您的示例中,5和7大于3),因此代码进入else分支...

  resultArr = filterMax(resultArr);

...并且什么也不返回(又名 undefined )。您可能想要

 return filterMax(resultArr);

总而言之:

function getMax(...numbers) {
function filterMax(numbers) {
const first = numbers[0];
const bigger = numbers.filter(function(value) {
return value > first;
});

if (bigger.length == 0) {
return first;
} else {
return filterMax(bigger);
}
};



return filterMax(numbers);
}

console.log(getMax(3, 7, 2, 5, 1, 4)); //output: 7

关于javascript - 为什么 "Array.prototype.slice(arguments)"给我一个空的 "[]"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57743921/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com