如何通过引用传递变量?

Teo*_*gır 0 javascript pass-by-reference

在其他编程语言中,我们使用&关键字通过引用传递变量.

例如,在PHP;

$a = 10;

function something(&$a){
    $a = 7;
};

something($a);

echo $a;
// 7
Run Code Online (Sandbox Code Playgroud)

我们怎样才能在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--];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在这个迭代器之外,我需要使用索引变量.但我只是得到旧的价值......我想得到当前的指数.

Mad*_*iha 5

JavaScript总是按值传递,JavaScript*中没有传递引用的概念.

您可以使用原子的原始版本来模仿效果:

let indexAtom = {value: 0};

function changeIndex(atom) {
  atom.value = 5;
}

changeIndex(indexAtom);

assert(indexAtom.value === 5);
Run Code Online (Sandbox Code Playgroud)

我会说,如果你需要这个,你通常会有代码味道,需要重新思考你的方法.

在您的情况下,您应该使用闭包来实现相同的效果:

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--];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

*一个常见的误解是对象是通过引用传递的,它令人困惑,因为对象的"值"也被称为"引用",程序员和命名事物.对象也是按值传递,但对象的值是一个特殊的"东西",称为"引用"或其"身份".这允许多个变量对同一对象保持相同的"引用".