如何在javascript中传递字符串值作为引用并在那里进行更改

Sha*_*pta 5 javascript string jquery pass-by-reference

如何在javascript中通过引用传递字符串值.

我想要这种功能.

    //Library.js
    function TryAppend(strMain,value)
    {
    strMain=strMain+value;
    return true;
    }

    //pager.aspx

    function validate()
    {
    str="Checking";
    TryAppend(str,"TextBox");
    alert(str); //expected result "Checking" TextBox
    //result being obtained "Checking"    
    }
Run Code Online (Sandbox Code Playgroud)

这该怎么做.?

djd*_*d87 4

在 JS 中不能通过引用传递值。您可以创建一个带有函数的对象来为您执行此操作:

function TryAppend(originalValue) {

    // Holds the value to return
    this.Value = originalValue;

    // The function joins the two strings
    this.Append = function (append) { 
        this.Value+=append; 
        return true;
    }

}
Run Code Online (Sandbox Code Playgroud)

然后您可以在任何方法中使用它,如下所示:

function AnyProcedure() {

    var str = "Checking";
    var append = new TryAppend(str);
    if (append.Append("TextBox")) {
        alert(append.Value);  // Will give "CheckingTextBox"
    }

}
Run Code Online (Sandbox Code Playgroud)

每次调用追加时,都会附加值字符串。IE

如果你随后这样做了:

append.Append(" Foo");
Run Code Online (Sandbox Code Playgroud)

append.Value等于CheckingTextBox Foo