javascript - 如何通过引用传递变量?
问题描述
在其他编程语言中,我们使用&
关键字通过引用传递变量。
例如,在 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--];
}
}
}
*一个常见的误解是对象是通过引用传递的,这很容易混淆,因为一个对象的“值”也被称为它的“引用”,程序员和命名事物。对象也是按值传递的,但对象的值是一种特殊的“事物”,称为“引用”或“身份”。这允许多个变量对同一个对象持有相同的“引用”。
推荐阅读
- android - InputMethodService 的仪器测试用例
- java - java的静态方法中的参数是线程安全的吗?
- python - 排序坐标
- kubernetes - 与 prometheus 一起使用时,kubernetes cAdvisor 是否也包含主机 (OS) 指标?
- android - 预览帧在 camera2 API 中冻结
- php - 从字段数据库中获取数据
- php - 使用 Join, Max + groupBy orderBy Query Builder Laravel
- .htaccess - 使用 htaccess 删除查询字符串和参数
- x86 - ELF - .symtab 部分
- c# - 自动转换为派生类型而不检查派生类型?