相当于 php $$ 美元的 javascript

发布于 2024-09-29 02:33:48 字数 2372 浏览 3 评论 0原文

  1. 我在名为 validate 的函数中声明了一个名为 cont 的局部变量。
  2. 我正在从 validate 内部调用一个函数进程。
  3. 我将字符串“cont”作为参数发送给验证函数。
  4. 在使用字符串“cont”的处理函数中,我想访问javascript局部变量的值,例如window['cont']。但我不确定。
  5. 我想做的是尝试访问 php 中的 $GLOBALS 或 $$ 等变量。

这是我所做的一个例子。

<script>

function process(str)
{
   alert(window[str]);
}

function validate()
{
   var cont='once there lived a king named midas';
   process('cont')
}

validate();

</script>

原因是我将大部分表单作为ajax 进行。我不想创建这样的请求字符串。

var param = "command=insert&content=" + encodeURIComponent(cont);

我想这样做。

var param = makeParam('command,[insert],content,(cont)');

我在 makeparam 中所做的是使用正则表达式来提取键值对。 所以我从 (cont) 获取字符串 cont 并将其替换为窗口变量,如 window[cont]。 cont 将包含字符串“cont”。

那么我们如何通过使用变量名称作为字符串来获取变量的内容呢?

所以我正在寻找相当于 php 的 $$

Edited

代码的一部分,其中我提取 (cont) 内部的 cont,这意味着我想要 () 之间的字符串内容。

nxt = str[i+1].match(/\((.*)\)$/)

if(nxt)param += '=' + encodeURIComponent(window[nxt[1]]);

param 的内容将是

"command=insert&content=once there lived a king"
// assume that once there lived a king is encoded

编辑。 Note2.

经过几次回复后,我正在编辑代码以添加此内容。

我正在尝试像 php 中的 $GLOBALS 那样做。

我还没有尝试过 $GLOBALS 是否也可以包含局部变量。

并了解到本地范围不会进入 $GLOBALS。


阅读 Felix King 的更新后进行更新。

我想使用一个函数来构造尽可能简单的查询字符串。像下面这样。

var param = makeParam('command,insert,/title/,/keywords/,/description/,mode,[1],fckcontent,(cont)');

// if it is a text without // or () then the it is a straight key value pair. so i will do comment=insert.

//if it is /title/ then the key is title and its value is an input elements value with id as title so title=getElementById('title')

//if it is mode,[1] then mode is the key and 1 is its direct value//

//if it is fckcontent,(cont) then fckcontent is the key and cont is a javascript local variable which will contain html content from a WYSIWYG editor.

// a sample result will be

 var param = "command=insert&keywords=somekeywords&description=somedescription&mode=1&fckcontent=<p>once there lived a king<p>

然后 casablanca 声明 $GlOBALS 将不包含局部范围变量,这与 javascript 中的方式相同。这是正确的。

  1. I have declared a local variable named cont in a function named validate.
  2. I am calling a function process from inside validate.
  3. I am sending the string 'cont' as argument to validate function.
  4. In the process function using the string 'cont' i want to access the javascript local variable's value like window['cont']. But i get undefined.
  5. What i am trying to do is trying to access variables like $GLOBALS in php or $$.

Here is an example of what i did.

<script>

function process(str)
{
   alert(window[str]);
}

function validate()
{
   var cont='once there lived a king named midas';
   process('cont')
}

validate();

</script>

The reason is i do most of the forms as ajax. i dont want to make a request string like this.

var param = "command=insert&content=" + encodeURIComponent(cont);

i want to do like this.

var param = makeParam('command,[insert],content,(cont)');

what i do in makeparam is i use regular expression to extract key value pairs.
so i get the string cont from (cont) and i substitute it into window variable like window[cont]. cont will have the string 'cont'.

so how do we get the content of a variable by using the name of the variable as string?

so i am looking for javascript equivalent of php's $$

Edited

a part of the code where i extract cont which is inside (cont) which means i want the content of the string between ().

nxt = str[i+1].match(/\((.*)\)$/)

if(nxt)param += '=' + encodeURIComponent(window[nxt[1]]);

the content of param would be

"command=insert&content=once there lived a king"
// assume that once there lived a king is encoded

Edit. Note2.

After few more responses i am editing the code to add this.

I am trying to do like $GLOBALS in php.

I haven't tried whether $GLOBALS would cantain local variables too.

and learned that local scope will not come into $GLOBALS.


Update after reading Felix King's Update.

I want to use a function which will construct a query string as simpler as possible. like the following.

var param = makeParam('command,insert,/title/,/keywords/,/description/,mode,[1],fckcontent,(cont)');

// if it is a text without // or () then the it is a straight key value pair. so i will do comment=insert.

//if it is /title/ then the key is title and its value is an input elements value with id as title so title=getElementById('title')

//if it is mode,[1] then mode is the key and 1 is its direct value//

//if it is fckcontent,(cont) then fckcontent is the key and cont is a javascript local variable which will contain html content from a WYSIWYG editor.

// a sample result will be

 var param = "command=insert&keywords=somekeywords&description=somedescription&mode=1&fckcontent=<p>once there lived a king<p>

and then casablanca stated that $GlOBALS will not contain local scope variables and that is the same way in javascript. that's right.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

ま昔日黯然 2024-10-06 02:33:48

您的代码是正确的,但您的期望是错误的。 PHP 中的 $GLOBALS 包含局部变量,同样的情况也适用于 JavaScript 中的windowcontvalidate 本地的,因此显然不能从 process 访问它。

在 PHP 中,您需要在函数内显式地将变量声明为全局变量。在 JavaScript 中,它的工作方式正好相反:使用 var 声明的任何变量都是局部的,任何声明的变量都是全局的。

Your code is correct, but what you're expecting is wrong. $GLOBALS in PHP does not include local variables, and the same thing applies to window in JavaScript. cont is local to validate, so obviously it can't be accessed from process.

In PHP, you need to explicitly declare a variable as global inside a function. In JavaScript, it works the other way round: any variables declared using var are local, anything that is not declared is global.

寄离 2024-10-06 02:33:48

正如其他人所建议的,您将无法在代码中的其他地方访问本地范围内的变量。

您最初发布的代码是:

function process(str) {
    alert(window[str]); // This will alert 'once there lived a king named midas'
} 

function validate() {
    var cont = 'once there lived a king named midas';
    process('cont'); 
}

validate();

另一种选择(而不是将所有内容都放在“窗口”变量映射中)是创建您自己的映射。

所以你的代码将变成:

var variables = { }

function process(str) {
    alert(variables[str]); // This will alert 'once there lived a king named midas'
}

function validate() {
    variables['cont'] = 'once there lived a king named midas';
    process('cont');
}

validate();

所有这一切都是在创建一个全局映射,你可以添加它并使用字符串进行索引。

As others have suggested, you wont be able to access variables in local scope elsewhere in your code.

The code you originally posted was:

function process(str) {
    alert(window[str]); // This will alert 'once there lived a king named midas'
} 

function validate() {
    var cont = 'once there lived a king named midas';
    process('cont'); 
}

validate();

Another option (rather than putting everything in the 'window' variables map), is to create your own map.

So your code would become:

var variables = { }

function process(str) {
    alert(variables[str]); // This will alert 'once there lived a king named midas'
}

function validate() {
    variables['cont'] = 'once there lived a king named midas';
    process('cont');
}

validate();

All this is doing is creating a global map which you can add to and index using strings.

浮世清欢 2024-10-06 02:33:48
function validate()
{
   var cont='once there lived a king named midas';
   process('cont')
}

cont 是在函数的本地作用域中定义的,而不是在全局作用域中定义的。要么只做

cont='once there lived a king named midas';

(不带var),要么

window.cont='once there lived a king named midas';

更新:

但是为什么你要在解析字符串时经历这么多麻烦呢?你为什么不这样做:

var param = makeParam({command: 'insert', content: encodeURIComponent(cont)});
function validate()
{
   var cont='once there lived a king named midas';
   process('cont')
}

cont is defined in the local scope of the function, not in global scope. Either do just

cont='once there lived a king named midas';

(without var) or

window.cont='once there lived a king named midas';

Update:

But why do you want to go through so much trouble with parsing strings? Why don't you do:

var param = makeParam({command: 'insert', content: encodeURIComponent(cont)});
眼眸 2024-10-06 02:33:48

我试图理解为什么您需要将变量作为字符串传递,以及为什么您想通过 window 对象访问 cont 。这看起来就像您期望代码执行的操作:

process = function (str) {
    alert(str); // This will alert 'once there lived a king named midas'
}

validate = function () {
    var cont = 'once there lived a king named midas';
    process(cont);
}

validate();

仅供参考:声明全局变量通常被认为是不好的做法,特别是在您似乎不需要它们的情况下。 (不过,我可能会错;我不完全确定你想要完成什么)

编辑:我建议使用一些函数并传递一些变量,而不是用 < code>eval() 式的变量引用。例如,您可以像这样实现 makeParam

var cont = 'Boggis, Bunce, and Bean.',
    makeParam = function(str) {
        var param = '',
            i = 0,
            arg = str.split(','),
            l = arg.length;
        while (i < l) {
            if (arg[i + 1].match(/\([a-zA-Z]+\)/)) { // No reason to capture
                param += [arg[1], cont].join('=');
                i += 2;
            } else if (arg[i].match(/\/[a-zA-Z]+\//)) { // No reason to capture
                param += [
                    arg[i], 
                    document.getElementById(arg[i]).value
                ].join('=');
                i += 1;
            } else {
                param += [arg[i], arg[i + 1]].join('=');
                i += 2;
            }
            param += (i + 1 === l) ? '' : '&';
        }
        return param;
    };
param = makeParam('command,insert,/title/,/keywords/,/description/,mode,[1],fckcontent, (cont)');
param === 'command=insert&\
         keywords=somekeywords&\
         description=somedescription&\
         mode=1&\
         fckcontent=Boggis, Bunce, and Bean.';

但是您可能希望将 cont 传递到 makeParam 函数中。

I'm trying to understand why you need to pass the variable as a string and why you want to access cont via the window object. This does what it looks like you expected your code to do:

process = function (str) {
    alert(str); // This will alert 'once there lived a king named midas'
}

validate = function () {
    var cont = 'once there lived a king named midas';
    process(cont);
}

validate();

FYI: It is generally considered bad practice to declare global variables, especially in a case like this where you don't appear to need them. (I could'd we wrong, though; I'm not entirely sure what you're trying to accomplish)

Edit: I would suggest using some functions and passing some variables around rather than mucking around with eval()-esque variable references. For example, you could implement makeParam like so:

var cont = 'Boggis, Bunce, and Bean.',
    makeParam = function(str) {
        var param = '',
            i = 0,
            arg = str.split(','),
            l = arg.length;
        while (i < l) {
            if (arg[i + 1].match(/\([a-zA-Z]+\)/)) { // No reason to capture
                param += [arg[1], cont].join('=');
                i += 2;
            } else if (arg[i].match(/\/[a-zA-Z]+\//)) { // No reason to capture
                param += [
                    arg[i], 
                    document.getElementById(arg[i]).value
                ].join('=');
                i += 1;
            } else {
                param += [arg[i], arg[i + 1]].join('=');
                i += 2;
            }
            param += (i + 1 === l) ? '' : '&';
        }
        return param;
    };
param = makeParam('command,insert,/title/,/keywords/,/description/,mode,[1],fckcontent, (cont)');
param === 'command=insert&\
         keywords=somekeywords&\
         description=somedescription&\
         mode=1&\
         fckcontent=Boggis, Bunce, and Bean.';

But you'd probably want to pass cont into your makeParam function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文