如何在 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"
}
如何做到这一点。 ?
最佳答案
您不能在 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;
}
}
然后您可以在任何方法中使用它,如下所示:
function AnyProcedure() {
var str = "Checking";
var append = new TryAppend(str);
if (append.Append("TextBox")) {
alert(append.Value); // Will give "CheckingTextBox"
}
}
每次调用 append 时,都会附加值字符串。即
如果你这样做了:
append.Append(" Foo");
append.Value
等于 CheckingTextBox Foo。
关于javascript - 如何在javascript中将字符串值作为引用传递并在那里进行更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3246842/