How to change the value of an array element through javascript?

I want to create a button that changes the value of an element in an array. I am trying to do this with the following code, but the element is not changing. As a newcomer to self-study, I will probably miss something very obvious, and I would appreciate it if someone could point this out to me.

Thank you for your responses!

<!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>
+3
source share
2 answers
function uClicked(){ // remove the parameter.

The parameter is not needed and hides the real variable fer.

Since it ferwas declared in the outer scope, the function uClickedcan access it.

Fixed Code:

var fer=[];

for (i=0; i< 15; i++){
        fer[i]=i+1;
}

function uClicked(){
    fer[12] = 10; 
    alert(fer[12]);
}
+6
source

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>

Work 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>
+3
source

All Articles