How can I pass a string value by reference in javascript.
I want this kind of functionality.
//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 "Ch开发者_StackOverflow中文版ecking"
}
How to do this. ?
You cannot pass a value by reference in JS. You could create an object with a function to do this for you:
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;
}
}
You can then use this in any method as follows:
function AnyProcedure() {
var str = "Checking";
var append = new TryAppend(str);
if (append.Append("TextBox")) {
alert(append.Value); // Will give "CheckingTextBox"
}
}
Each time you call append, the Value string will be appended to. I.e.
If you then did:
append.Append(" Foo");
append.Value
would equal CheckingTextBox Foo.
You need to return the String instead of true
!!
function TryAppend(strMain,value) {
strMain=strMain+value;
return strMain; //you need return the 'String Value' to use in it another method
}
//pager.aspx
function validate() {
str="Checking";
str = TryAppend(str,"TextBox");
alert(str); //expected result "Checking" TextBox
//result being obtained "Checking"
}
Create a global variable (say gblstrMain) outside the function TryAppend and then set its value to strMain inside the function.
var gblstrMain;
function TryAppend(strMain,value)
{
strMain=strMain+value;
gblstrMain = strMain;
return true;
}
//pager.aspx
function validate()
{
str="Checking";
TryAppend(str,"TextBox");
str = gblstrMain;
alert(str); //expected result "Checking" TextBox
//result being obtained "Checking"
}
Since you are particular about "return true" in the TryAppend function, we can achieve by this workaround.
精彩评论