gpt4 book ai didi

javascript - Javascript 中的变量引用

转载 作者:行者123 更新时间:2023-11-29 17:17:59 25 4
gpt4 key购买 nike

我之前在思考一些事情。我想检查一个函数是否已经放入数组中。如果是则抛出异常。我用控制台做了这个小测试......

enter image description here

所以我想我可以说对象总是只是引用,并且在将 a 设置为 x 之后我可以更改 xa 也会受到影响吗?

这是否意味着条件 x = a 不管怎样,这就是我想要的。

使用它来检查函数/对象是否已经在数组中我可以正确地做到这一点......

enter image description here

有更好的方法吗?

这是否也意味着如果我将一个变量传递给一个函数并在该函数中改变它,它也会在该函数之外发生改变?

编辑

我想我对这个小测试的突变是正确的。但我不明白为什么它在第二个示例的第一个日志中出现栏

enter image description here

enter image description here

编辑结束

示例 1:

var x = function(){console.log("hello")}; var a = function(){console.log("hello")}; 

console.log(x == a); //comes out false

//Set a as x
a = x;

console.log(x == a); //comes out true

示例 2:

Array.prototype.Contains = Array.prototype.Contains || function (obj) {
return this.indexOf(obj) != -1;
};

var x = function(){console.log("hello")}; var a = function(){console.log("hello")};

var z = a;

console.log(x == a); //comes out false

var l = [];
l.push(x);

//Set a as x
a = x;

l.push(a);

console.log(x == a); //comes out true

console.log(l.Contains(x)); //Should come out true
console.log(l.Contains(a)); //Should come out true
console.log(l.Contains(z)); //Should come out false

最佳答案

你的问题对我来说不是很清楚,但我会尽力回答。

改进功能

可以简化您的函数以利用 indexOf 函数。

Array.prototype.Contains = Array.prototype.Contains || function (obj) {
return this.indexOf(obj) >= 0;
};

我还想指出,在您的实现中,您正在遍历所有内容,而您可以通过在 if 中返回来提前退出。

Array.prototype.Contains = Array.prototype.Contains || function (obj) {
var i;
for (i = 0; i < this.length; i += 1) {
if (this[i] === obj) {
return true;
}
}
return false;
};

x == a

我想你明白了,但只是想澄清一下,xa 最初是不同的,因为它们引用了不同的函数。当您设置 x = a 时,它们都指向最初在 x 中声明的函数,因此是相同的。尽管这些函数在实现方面是相同的,但它们都是构造出来的,然后放置在内存的不同部分。

关于javascript - Javascript 中的变量引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15468836/

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