我注意到 JavaScript 中有一些我不理解的行为。据我了解,对于传递给函数的原始类型,它们是按值传递的。如果我们传递一个对象,它们将通过引用传递。我想做的是将重复部分封装到函数中来缩短我的代码;该函数的作用是获取一个指向链表中节点的节点对象,对其值执行某些操作,然后将其移动到链表中的下一个节点。然而事实并非如此。我在这里做了一个简单的例子:
var testObj = {};
testObj.val = 5;
testObj.next = {
val: 7,
next: null
}
var temp = testObj;
console.log("Val before: ", temp.val); //prints 5
function test(node) {
console.log(node.val); //prints 5
node = node.next;
console.log(node.val); //prints 7
}
test(temp);
console.log("Val after: ", temp.val); //prints 5??
首先,我创建一个带有值的测试节点和一个指向列表中也有值的下一个节点的下一个字段。我创建另一个节点,该节点指向列表中的第一个节点(当您想要迭代列表时,这是常见的,您不想失去对根节点的跟踪。)
我很困惑为什么你可以做这样的事情
function test(node) {
node.val = 100;
}
console.log(temp.val); //prints 100
并且值(value)的变化保持不变;但如果我使节点指向列表中的下一个项目,则该更改不会保留。
最佳答案
Javascript 将值复制到您将其作为参数传递给的函数。
var temp = testObj; // temp is defined in this scope
console.log("Val before: ", temp.val); //prints 5
function test(node) { //node is defined in those scope, and is not a reference.
console.log(node.val); //prints node
node = node.next;
//if you wouldve done node.value = 10, it wouldve changed for temp as value is encapsulated
console.log(node.val); //prints node
}
test(temp); //temp is still the same as it was defined as you didn't change it
console.log("Val after: ", temp.val); //prints temp
如果你想让参数成为你传递的对象的引用,你需要将它封装在另一个对象中,也就是说,如果你在函数中再次设置参数,对旧对象的引用就会消失。 看看这个question
关于javascript - 对于这个链表示例,JavaScript 如何处理传递给函数的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34927439/