I simply want to access the value of array status from another function. However, the alert is giving me value as undefined. Here's my code:
Test.php:
<html>
<body>
<script>
var status=[];
status[0]='1';
calculateInput();
function calculateInput(){
alert(status[0]);
}
</script>
</body>
</html>
hichris123
10.3k15 gold badges58 silver badges70 bronze badges
2 Answers 2
You are colliding with window.status:
function calculateInput () {
alert( status === window.status ); // true
}
To avoid this, rename your array or get out of the global scope:
(function IIFE () {
var status = [];
status[0] = "1";
calculateInput();
function calculateInput () {
alert( status[0] );
}
}());
answered Mar 23, 2014 at 18:50
Sampson
269k76 gold badges546 silver badges570 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Dikshay Poojary
actually I also want to use the array in another function. So I have to use global.
Sampson
@DikshayPoojary You don't need to put it in the global scope. If you still want to, namespace it or given it a different name.
andrew.fox
JavaScript is great, you can overwrite
undefined "constant", but window.status is protected... :)Change your variable name from status to something else
ex.
<html>
<body>
<script>
var mystatus=[];
mystatus[0]='1';
calculateInput();
function calculateInput(){
alert(mystatus[0]);
}
</script>
</body>
</html>
answered Mar 23, 2014 at 18:53
Chris
2,4561 gold badge29 silver badges41 bronze badges
Comments
default
calculateInput()