如何在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

最好的方法是什么?


当前回答

另一种通过引用传递任何(局部的,基本的)变量的方法是通过eval“动态”地用闭包包装变量。这也适用于“use strict”。(注意:注意eval对JavaScript优化器不友好,并且变量名周围缺少引号可能会导致不可预测的结果)

"use strict"

// Return text that will reference variable by name (by capturing that variable to closure)
function byRef(varName){
    return "({get value(){return "+varName+";}, set value(v){"+varName+"=v;}})";
}

// Demo

// Assign argument by reference
function modifyArgument(argRef, multiplier){
    argRef.value = argRef.value * multiplier;
}

(function(){
    var x = 10;

    alert("x before: " + x);
    modifyArgument(eval(byRef("x")), 42);
    alert("x after: " + x);
})()

现场示例:https://jsfiddle.net/t3k4403w/

其他回答

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

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"]

另一种通过引用传递任何(局部的,基本的)变量的方法是通过eval“动态”地用闭包包装变量。这也适用于“use strict”。(注意:注意eval对JavaScript优化器不友好,并且变量名周围缺少引号可能会导致不可预测的结果)

"use strict"

// Return text that will reference variable by name (by capturing that variable to closure)
function byRef(varName){
    return "({get value(){return "+varName+";}, set value(v){"+varName+"=v;}})";
}

// Demo

// Assign argument by reference
function modifyArgument(argRef, multiplier){
    argRef.value = argRef.value * multiplier;
}

(function(){
    var x = 10;

    alert("x before: " + x);
    modifyArgument(eval(byRef("x")), 42);
    alert("x after: " + x);
})()

现场示例:https://jsfiddle.net/t3k4403w/

其实很简单。问题在于,一旦传递了经典参数,您就会被限定在另一个只读区域。

解决方案是使用JavaScript的面向对象设计来传递参数。这与将参数放在全局/作用域变量中是一样的,但更好…

function action(){
  /* Process this.arg, modification allowed */
}

action.arg = [["empty-array"], "some string", 0x100, "last argument"];
action();

你也可以承诺一些东西来享受著名的连锁店: 这就是全部,像承诺一样的结构

function action(){
  /* Process this.arg, modification allowed */
  this.arg = ["a", "b"];
}

action.setArg = function(){this.arg = arguments; return this;}

action.setArg(["empty-array"], "some string", 0x100, "last argument")()

或者更好的是……

action.setArg(["empty-array"],"some string",0x100,"last argument").call()

我个人不喜欢各种编程语言提供的“引用传递”功能。也许这是因为我刚刚发现函数式编程的概念,但是当我看到函数会产生副作用(比如通过引用来操纵参数)时,我总是起鸡皮疙瘩。我个人强烈拥护“单一责任”原则。

恕我直言,函数应该使用return关键字只返回一个结果/值。我不修改参数/实参,而是返回修改后的参数/实参值,并将任何所需的重赋留给调用代码。

但有时(希望很少),需要从同一个函数返回两个或多个结果值。在这种情况下,我会选择将所有这些结果值包含在单个结构或对象中。同样,处理任何重分配都应该由调用代码来决定。

例子:

假设通过在参数列表中使用'ref'这样的特殊关键字来支持传递参数。我的代码可能是这样的:

//The Function
function doSomething(ref value) {
    value = "Bar";
}

//The Calling Code
var value = "Foo";
doSomething(value);
console.log(value); //Bar

相反,我更喜欢这样做:

//The Function
function doSomething(value) {
    value = "Bar";
    return value;
}

//The Calling Code:
var value = "Foo";
value = doSomething(value); //Reassignment
console.log(value); //Bar

当我需要编写一个返回多个值的函数时,我也不会使用引用传递的参数。所以我会避免这样的代码:

//The Function
function doSomething(ref value) {
    value = "Bar";

    //Do other work
    var otherValue = "Something else";

    return otherValue;
}

//The Calling Code
var value = "Foo";
var otherValue = doSomething(value);
console.log(value); //Bar
console.log(otherValue); //Something else

相反,我实际上更喜欢在对象中返回两个新值,就像这样:

//The Function
function doSomething(value) {
    value = "Bar";

    //Do more work
    var otherValue = "Something else";

    return {
        value: value,
        otherValue: otherValue
    };
}

//The Calling Code:
var value = "Foo";
var result = doSomething(value);
value = result.value; //Reassignment
console.log(value); //Bar
console.log(result.otherValue);

这些代码示例非常简化,但它大致演示了我个人如何处理这些东西。它帮助我把各种责任放在正确的位置。

快乐的编码。:)

如果你想通过引用传递变量,一个更好的方法是通过在对象中传递参数,然后使用window开始更改值:

window["varName"] = value;

例子:

// Variables with first values
var x = 1, b = 0, f = 15;


function asByReference (
    argumentHasVars = {},   // Passing variables in object
    newValues = [])         // Pass new values in array
{
    let VarsNames = [];

    // Getting variables names one by one
    for(let name in argumentHasVars)
        VarsNames.push(name);

    // Accessing variables by using window one by one
    for(let i = 0; i < VarsNames.length; i += 1)
        window[VarsNames[i]] = newValues[i]; // Set new value
}

console.log(x, b, f); // Output with first values

asByReference({x, b, f}, [5, 5, 5]); // Passing as by reference

console.log(x, b, f); // Output after changing values