Javascript 如何通过javascript更改数组元素的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10690039/
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
How to change value of an array element through javascript?
提问by glin yon
I want to make a button that changes the value of an element in an array. I am trying to do it by the following code but the element does not change. As a self learning beginner, I am probably missing something very obvious and I would appreciate if someone can point that out to me.
我想制作一个按钮来更改数组中元素的值。我试图通过以下代码来做到这一点,但元素没有改变。作为一个自学初学者,我可能遗漏了一些非常明显的东西,如果有人能向我指出这一点,我将不胜感激。
Thank you for your answers!
谢谢您的回答!
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Change Array Value</title>
</head>
<body>
<textarea id="log2"></textarea>
<input type="button" onClick="uClicked();" value="Click!">
<script>
var fer=[];
for (i=0; i< 15; i++){
fer[i]=i+1;
}
function uClicked(fer){
fer[12] = 10;
return fer[12];
}
log2.value = "fer[12]= " + fer[12];
</script>
</body>
</html>
回答by gdoron is supporting Monica
function uClicked(){ // remove the parameter.
The parameter isn't needed, and is hiding the real fervariable.
不需要参数,并且隐藏了真实fer变量。
Because ferwas declared in outer scope, uClickedfunction can access it.
因为fer是在外部作用域中声明的,uClicked函数可以访问它。
Fixed code:
固定代码:
var fer=[];
for (i=0; i< 15; i++){
fer[i]=i+1;
}
function uClicked(){
fer[12] = 10;
alert(fer[12]);
}
回答by Pencho Ilchev
Your code with comments
带注释的代码
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Change Array Value</title>
</head>
<body>
<textarea id="log2"></textarea>
<input type="button" onClick="uClicked();" value="Click!">
<script>
var fer=[];
for (i=0; i< 15; i++){ //use var i, otherwise you are putting i in the global scope
fer[i]=i+1;
}
function uClicked(fer){ // fer is undefined because you are not passing argument when you call the function
fer[12] = 10;
return fer[12];
}
log2.value = "fer[12]= " + fer[12]; //log2 is not defined.
</script>
</body>
</html>
The working code:
工作代码:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Change Array Value</title>
</head>
<body>
<textarea id="log2"></textarea>
<input type="button" onclick="uClicked();" value="Click!" />
<script type="text/javascript">
var fer = [];
for(var i; i < 15; i++){
fer[i]=i+1;
}
var log2 = document.getElementById("log2");
function uClicked(){
fer[12] = 10;
log2.value = "fer[12]= " + fer[12];
return fer[12];
}
</script>
?
?</body>
</html>

