Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change value of an array element through javascript?

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>
like image 533
glin yon Avatar asked Dec 02 '25 05:12

glin yon


1 Answers

function uClicked(){ // remove the parameter.

The parameter isn't needed, and is hiding the real fer variable.

Because fer was declared in outer scope, uClicked function can access it.

Fixed code:

var fer=[];

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

function uClicked(){
    fer[12] = 10; 
    alert(fer[12]);
}
like image 63
gdoron is supporting Monica Avatar answered Dec 03 '25 18:12

gdoron is supporting Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!