如何在JavaScript中通过引用传递变量?

我有三个变量,我想对它们执行一些操作,所以我想把它们放在一个for循环中,并对每个变量执行操作。

伪代码:

myArray = new Array(var1, var2, var3);
for (var x = 0; x < myArray.length; x++){
    // Do stuff to the array
    makePretty(myArray[x]);
}
// Now do stuff to the updated variables

最好的方法是什么?


当前回答

撇开“参考资料传递”的讨论不谈,那些仍然在寻找上述问题的解决方案的人可以使用:

const myArray = new Array(var1, var2, var3);
myArray.forEach(var => var = makePretty(var));

其他回答

JavaScript中没有“引用传递”。你可以传递一个对象(也就是说,你可以按值传递一个对象的引用),然后让一个函数修改对象的内容:

function alterObject(obj) {
  obj.foo = "goodbye";
}

var myObj = { foo: "hello world" };

alterObject(myObj);

alert(myObj.foo); // "goodbye" instead of "hello world"

如果需要,可以使用数值索引遍历数组的属性,并修改数组的每个单元格。

var arr = [1, 2, 3];

for (var i = 0; i < arr.length; i++) { 
    arr[i] = arr[i] + 1; 
}

需要注意的是,“引用传递”是一个非常具体的术语。这并不仅仅意味着可以将引用传递给一个可修改的对象。相反,这意味着可以通过允许函数在调用上下文中修改该值的方式传递简单变量。所以:

 function swap(a, b) {
   var tmp = a;
   a = b;
   b = tmp; //assign tmp to b
 }

 var x = 1, y = 2;
 swap(x, y);

 alert("x is " + x + ", y is " + y); // "x is 1, y is 2"

在c++这样的语言中,这样做是可能的,因为该语言确实(在某种程度上)具有引用传递。

edit — this recently (March 2015) blew up on Reddit again over a blog post similar to mine mentioned below, though in this case about Java. It occurred to me while reading the back-and-forth in the Reddit comments that a big part of the confusion stems from the unfortunate collision involving the word "reference". The terminology "pass by reference" and "pass by value" predates the concept of having "objects" to work with in programming languages. It's really not about objects at all; it's about function parameters, and specifically how function parameters are "connected" (or not) to the calling environment. In particular, note that in a true pass-by-reference language — one that does involve objects — one would still have the ability to modify object contents, and it would look pretty much exactly like it does in JavaScript. However, one would also be able to modify the object reference in the calling environment, and that's the key thing that you can't do in JavaScript. A pass-by-reference language would pass not the reference itself, but a reference to the reference.

编辑-这里有一篇关于这个主题的博客文章。(注意那篇文章的注释,解释了c++并没有真正的引用传递。这是真的。然而,c++所拥有的是创建对普通变量的引用的能力,可以在函数调用时显式地创建指针,也可以在调用其参数类型签名要求这样做的函数时隐式地创建指针。这些都是JavaScript不支持的关键。)

我喜欢在JavaScript中解决引用的不足,就像这个例子所显示的那样。

这样做的本质是,您不必尝试创建一个通过引用。相反,您可以使用返回功能,并使其能够返回多个值。因此,不需要在数组或对象中插入值。

var x = "First"; var y = "Second"; var z = "Third"; log('Before call:',x,y,z); with (myFunc(x, y, z)) {x = a; y = b; z = c;} // <-- Way to call it log('After call :',x,y,z); function myFunc(a, b, c) { a = "Changed first parameter"; b = "Changed second parameter"; c = "Changed third parameter"; return {a:a, b:b, c:c}; // <-- Return multiple values } function log(txt,p1,p2,p3) { document.getElementById('msg').innerHTML += txt + '<br>' + p1 + '<br>' + p2 + '<br>' + p3 + '<br><br>' } <div id='msg'></div>

由于我们没有javascript的引用传递功能,唯一的方法是让函数返回值,并让调用者分配它:

So

"makePretty(myArray[x]);"

应该是

"myArray[x] = makePretty(myArray[x]);"

这是在函数内部需要赋值的情况下,如果只需要突变,那么传递对象并突变它就足够了

I've been playing around with syntax to do this sort of thing, but it requires some helpers that are a little unusual. It starts with not using 'var' at all, but a simple 'DECLARE' helper that creates a local variable and defines a scope for it via an anonymous callback. By controlling how variables are declared, we can choose to wrap them into objects so that they can always be passed by reference, essentially. This is similar to one of the Eduardo Cuomo's answer above, but the solution below does not require using strings as variable identifiers. Here's some minimal code to show the concept.

function Wrapper(val){
    this.VAL = val;
}
Wrapper.prototype.toString = function(){
    return this.VAL.toString();
}

function DECLARE(val, callback){
    var valWrapped = new Wrapper(val);    
    callback(valWrapped);
}

function INC(ref){
    if(ref && ref.hasOwnProperty('VAL')){
        ref.VAL++; 
    }
    else{
        ref++;//or maybe throw here instead?
    }

    return ref;
}

DECLARE(5, function(five){ //consider this line the same as 'let five = 5'
console.log("five is now " + five);
INC(five); // increment
console.log("five is incremented to " + five);
});

其实有一个很好的解决方案:

function updateArray(context, targetName, callback) {
    context[targetName] = context[targetName].map(callback);
}

var myArray = ['a', 'b', 'c'];
updateArray(this, 'myArray', item => {return '_' + item});

console.log(myArray); //(3) ["_a", "_b", "_c"]