如何通过引用传递变量?
How to pass variable by reference?
在其他编程语言中,我们使用 &
关键字通过引用传递变量。
例如,在php;
$a = 10;
function something(&$a){
$a = 7;
};
something($a);
echo $a;
// 7
我们如何在 javascript 中做到这一点?
当用户单击向右或向左箭头时,我正在尝试获取下一个或上一个。按数组索引排列的图像;
list: function (index) {
let items = this.images;
return {
next: function () {
if (index > items.length -1) {
index = 0;
}
return items[index++];
},
prev: function () {
if (index < 0) {
index = items.length -1;
}
return items[index--];
}
}
}
在这个迭代器之外,我需要使用索引变量。但是我只得到旧值...我想得到当前索引。
JavaScript 总是按值传递,JavaScript*.
中没有按引用传递的概念
您可以使用原子的原始版本来模拟效果:
let indexAtom = {value: 0};
function changeIndex(atom) {
atom.value = 5;
}
changeIndex(indexAtom);
assert(indexAtom.value === 5);
我会说如果你需要这个,你通常有代码味道,需要重新考虑你的方法。
在你的情况下,你应该使用闭包来达到同样的效果:
list: function (startingIndex = 0) {
let items = this.images;
let index = startingIndex; // note that index is defined here, inside of the function
return {
next: function () {
// index taken from closure.
if (index > items.length -1) {
index = 0;
}
return items[index++];
},
prev: function () {
// same index as the next() function
if (index < 0) {
index = items.length -1;
}
return items[index--];
}
}
}
* 一个常见的误解是对象是按引用传递的,这很令人困惑,因为对象的 "value" 也被称为它的 "reference" ,程序员和命名的东西。对象也是按值传递的,但是对象的值是一个特殊的 "thing",称为它的 "reference" 或它的 "identity"。这允许多个变量将相同的 "reference" 保存到同一对象。
在其他编程语言中,我们使用 &
关键字通过引用传递变量。
例如,在php;
$a = 10;
function something(&$a){
$a = 7;
};
something($a);
echo $a;
// 7
我们如何在 javascript 中做到这一点?
当用户单击向右或向左箭头时,我正在尝试获取下一个或上一个。按数组索引排列的图像;
list: function (index) {
let items = this.images;
return {
next: function () {
if (index > items.length -1) {
index = 0;
}
return items[index++];
},
prev: function () {
if (index < 0) {
index = items.length -1;
}
return items[index--];
}
}
}
在这个迭代器之外,我需要使用索引变量。但是我只得到旧值...我想得到当前索引。
JavaScript 总是按值传递,JavaScript*.
中没有按引用传递的概念您可以使用原子的原始版本来模拟效果:
let indexAtom = {value: 0};
function changeIndex(atom) {
atom.value = 5;
}
changeIndex(indexAtom);
assert(indexAtom.value === 5);
我会说如果你需要这个,你通常有代码味道,需要重新考虑你的方法。
在你的情况下,你应该使用闭包来达到同样的效果:
list: function (startingIndex = 0) {
let items = this.images;
let index = startingIndex; // note that index is defined here, inside of the function
return {
next: function () {
// index taken from closure.
if (index > items.length -1) {
index = 0;
}
return items[index++];
},
prev: function () {
// same index as the next() function
if (index < 0) {
index = items.length -1;
}
return items[index--];
}
}
}
* 一个常见的误解是对象是按引用传递的,这很令人困惑,因为对象的 "value" 也被称为它的 "reference" ,程序员和命名的东西。对象也是按值传递的,但是对象的值是一个特殊的 "thing",称为它的 "reference" 或它的 "identity"。这允许多个变量将相同的 "reference" 保存到同一对象。