gpt4 book ai didi

JavaScript 应用()

转载 作者:行者123 更新时间:2023-11-28 14:15:33 26 4
gpt4 key购买 nike

当我分别将数组和对象传递给 function.apply() 时,我得到 NaN 的 o/p,但是当我传递对象和数组时,我得到一个数字。为什么会发生这种情况?

由于数组也被视为对象,为什么我无法使用它来表示来自同一上下文的数组/

我尝试过更改变量调用的位置,但我知道只有当它是参数时顺序才重要。

function add() {
return arr[0] + arr[1] + this.a + this.b;
}
let obj = {
a: 1,

b: 2
};

let arr = [1, 2];

console.log(add.apply(arr, obj));
console.log(add.apply(obj, arr));

输出

NaN
6

最佳答案

也许图表可以提供帮助。您的函数不使用参数,因此您在 apply 的第二个参数中提供的内容(应该是值数组)并不重要。只有第一个参数(在函数体中成为 this)很重要。

当您使用 arr 调用时,this 指向参数中提供的 arr,但 arr也指向同一个对象,因为它是全局的并且不会在任何地方被覆盖:

function add() {
// 1 + 1 + undefined + undefined //=> NaN
return arr[0] + arr[1] + this.a + this.b;
} // | | | |
// +------+--------+---------+-----------+
// |
// V
let arr = [1, 2]; let obj = {a: 1, b: 2};
// ^
// `-----Nothing points to this

add.apply(arr) // equivalent to `add.apply(arr, obj)`, since `add` ignores parameters

当您使用 obj 调用时,this 指向参数中提供的 obj,并且 arr再次指向全局 arr 对象:

function add() {
// 1 + 2 + 1 + 2 //=> 6
return arr[0] + arr[1] + this.a + this.b;
} // | | | |
// +------+--------+ +-----------+
// | |
// V V
let arr = [1, 2]; let obj = {a: 1, b: 2};

add.apply(obj) // equivalent to `add.apply(obj, arr)`, since `add` ignores parameters

关于JavaScript 应用(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57661878/

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