Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript创建n个变量_Javascript_Variables - Fatal编程技术网

Javascript创建n个变量

Javascript创建n个变量,javascript,variables,Javascript,Variables,我有一个数组 var n = ["Joe", "Peter", "Mary", "Chris", "Dave", "Sally", "Pat", "John", "Larry", "Andrew"]; 我想为数组中的每个字符串创建一个变量,即 var Joe; var Peter; var Mary; 我曾经遇到过MatLab,但是有什么方法可以用Javascript实现这一点吗 这里有一个例子,我会怎么想做,但显然它不工作 我不建议这样做,但可以使用: va

我有一个数组

    var n = ["Joe", "Peter", "Mary", "Chris", "Dave", "Sally", "Pat", "John", "Larry", "Andrew"];
我想为数组中的每个字符串创建一个变量,即

    var Joe;
    var Peter;
    var Mary;
我曾经遇到过MatLab,但是有什么方法可以用Javascript实现这一点吗


这里有一个例子,我会怎么想做,但显然它不工作

我不建议这样做,但可以使用:

var i;
for(i=0; i<n.length; i++) {
    window[n[i]] = ...;
}
我建议使用以下方法将它们包装在对象中:

var i, holder = {};
for(i=0; i<n.length; i++) {
    holder [n[i]] = ...;
}

可以使用关联数组。所以它可能看起来像这样:

var array = {
     "John": 1,
     "Mary": 284
};
var index;
for (index = 0; index < n.length; ++index) {
    window[n[index]] = /*...whatever value you want the global to have...*/;
}
var index;
for (index = 0; index < n.length; ++index) {
    eval("var " + n[index]);
}
var names = {
    Joe: "...",
    Mary: "...",
    // etc...
}
然后通过数组[John]引用该值,并返回1

…有没有办法用Javascript实现这一点

不在一般情况下,不。呃,见下文。您可以使用全局变量执行此操作,如下所示:

var array = {
     "John": 1,
     "Mary": 284
};
var index;
for (index = 0; index < n.length; ++index) {
    window[n[index]] = /*...whatever value you want the global to have...*/;
}
var index;
for (index = 0; index < n.length; ++index) {
    eval("var " + n[index]);
}
var names = {
    Joe: "...",
    Mary: "...",
    // etc...
}
…这基本上是全局变量的情况,但使用的是对象而不是全局变量。但是再一次,除非你有一个很好的理由去做,否则没有什么意义,尽管它并不像创建一堆全局对象那样有害

好吧,那不是真的。您可以这样做:

var array = {
     "John": 1,
     "Mary": 284
};
var index;
for (index = 0; index < n.length; ++index) {
    window[n[index]] = /*...whatever value you want the global to have...*/;
}
var index;
for (index = 0; index < n.length; ++index) {
    eval("var " + n[index]);
}
var names = {
    Joe: "...",
    Mary: "...",
    // etc...
}

这将实际在当前范围中创建名为n的变量。我不推荐-

您可以创建如下对象:

var array = {
     "John": 1,
     "Mary": 284
};
var index;
for (index = 0; index < n.length; ++index) {
    window[n[index]] = /*...whatever value you want the global to have...*/;
}
var index;
for (index = 0; index < n.length; ++index) {
    eval("var " + n[index]);
}
var names = {
    Joe: "...",
    Mary: "...",
    // etc...
}
和访问:


名字。乔

为什么?这只会使事情复杂化。它们在JavaScript中被称为对象。我不会说这是不可能的,但对象肯定是更好的选择。@CookieMoster:啊,你说得对。谢谢你的轻推。