javascript 全局数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5619975/
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
javascript global array
提问by user569125
I am having below html code and trying to add new values to global array by onchanging of javascript function.I am trying to do like below way.But it is giving javascript errors.Please suggest anyone how to do this.
我有下面的 html 代码,并试图通过改变 javascript 函数来向全局数组添加新值。我正在尝试像下面那样做。但它给出了 javascript 错误。请建议任何人如何做到这一点。
<html>
<head>
<script>
var list=[];
function getList(value){
list=list(value);
}
</script>
</head>
<body>
<tr>
<td>
<select name="test" onchange="getList(this)">
<option id="1" value="one">One</option>
<option id="2" value="two">two</option>
</select>
</td>
</tr>
<tr>
<td>
<select name="test1" onchange="getList(this)">
<option id="3" value="three">three</option>
<option id="4" value="four">four</option>
</select>
</td>
</tr>
</body>
</html>
回答by Sangeet Menon
Change your Javascript
to the following
将您Javascript
的更改为以下
var list=new Array; ///this one way of declaring array in javascript
function getList(value){
list.push(value);//push function will insert values in the list array
}
回答by Kevin
Adding values to an array is quite simple, all you have to do is call the push(..)
method.
向数组添加值非常简单,您要做的就是调用该push(..)
方法。
Like so:
像这样:
var list = [ ];
list.push(1);
console.info(list); // Outputs: [ 1 ]
回答by Town
You're currently passing the entire select element to your function, rather than the selected value. You can pass the selected value like this:
您当前将整个 select 元素传递给您的函数,而不是选定的值。您可以像这样传递选定的值:
getList(this.options[this.selectedIndex].value)
Then you can use list.push(value)
in your function to add the selected value to your array.
然后您可以list.push(value)
在您的函数中使用将选定的值添加到您的数组中。
回答by RoToRa
The easiest way to add a value to an array in JavaScript, it to use the push
method (unless you need to support IE5):
JavaScript 中给数组添加值最简单的方法,就是使用push
方法(除非你需要支持 IE5):
function getList(value) {
list.push(value);
}
Two things:
两件事情:
In your case this would add references to the select elements to the list. That's most likely not what you want. What exactly do you want to add?
getList
isn't really a suitable name for that.addToList
would be probably better.
在您的情况下,这会将对选择元素的引用添加到列表中。这很可能不是您想要的。您究竟想添加什么?
getList
真的不是一个合适的名字。addToList
可能会更好。