javascript 将变量存储到数组javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19312596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:07:56  来源:igfitidea点击:

Store variable into array javascript

javascriptarraysvariables

提问by youaremysunshine

How to store the javascript variable into array?

如何将javascript变量存储到数组中?

I have these variable and I wish to store them into array:

我有这些变量,我希望将它们存储到数组中:

var name=document.forms["form"]["name"].value;
    var email=document.forms["form"]["email"].value;
    var mobile=document.forms["form"]["mobile"].value;
    var q1=document.forms["form"]["q1"].value;
    var q2=document.forms["form"]["q2"].value;
    var q3=document.forms["form"]["q3"].value;
    var l1=document.forms["form"]["logo1"].value;
    var l2=document.forms["form"]["logo2"].value;
    var l3=document.forms["form"]["logo3"].value;
    var p1=document.forms["form"]["photo1"].value;
    var p2=document.forms["form"]["photo2"].value;
    var p3=document.forms["form"]["photo3"].value;

回答by Sergio

var arr = [];
var name=document.forms["form"]["name"].value;
var email=document.forms["form"]["email"].value;
arr.push(name);
//etc

Using the .push()method

使用.push()方法

You could also serialize if you are going to post the form.

如果您要发布表单,也可以进行序列化。

回答by matewka

You can try with traditional array:

您可以尝试使用传统数组:

var myArray = [];
myArray.push(document.forms["form"]["name"].value);

The keys will be numeric (starting from 0).
Or, if you want to preserve string keys, like associative arraysin other languages, you can store your values as an object

键将是数字(从 0 开始)。
或者,如果您想保留字符串键,例如其他语言中的关联数组,您可以将您的值存储为一个对象

var myArray = {};
myArray["name"] = document.forms["form"]["name"].value;

回答by Elon Than

As simple as

就这么简单

var newArray = [];
newArray[0] = name;
newArray[1] = email;

...