I am trying to get load a variable from a array variable for my project but the value comes back as undefined I just used the console.log for the test output.
I want to learn how to use it after seeing others use on their projects and I want to do it to make my projects easier to manage.
I set it to trigger when the page loads up first thing.
Any help is welcome from the community.
My code if it helps solve it problem:
window.addEventListener('load',function(){
var values = [
odds_base = 10,
start_cash = 50
]
console.log(values.odds_base)
});
5 Answers 5
In this case I think you have to use an object like this one, instead of array:
window.addEventListener('load',function() {
var values = {
odds_base: 10,
start_cash: 50
};
console.log(values.odds_base);
});
3 Comments
JSON but just an object.You are using the wrong data structure here. Square brackets are used for arrays. You should use a javascript object here.
window.addEventListener('load',function(){
var values = {
odds_base: 10,
start_cash: 50
}
console.log(values.odds_base)
});
Comments
Or you can do like this
let values = {};
values.odds_base = 10;
values.start_cash = 50;
console.log(values.odds_base);
Comments
If that is array then you have to use variables like this
window.addEventListener('load',function(){
var values = [
odds_base = 10,
start_cash = 50
]
console.log(values);
console.log(odds_base);
console.log(start_cash);
});
When you assign array like this then Internally JavaScript first Creates the variable and then assign those variables in array
Otherwise convert that array to object and do like as follows
window.addEventListener('load',function(){
var values = {
odds_base : 10,
start_cash : 50
}
console.log(values);
console.log(values.odds_base);
console.log(values.start_cash);
});
Comments
The value of values looks like it should be an object and not an array as seen in your example i.e. values = [ a = 1, b = 2 ] should be values = { a: 1, b: 2 }
window.addEventListener('load', function(){
var values = {
odds_base: 10,
start_cash: 50
}
console.log(values.odds_base)
});
Tip: Declare the values variable outside the scope of the addEventListener callback if you wish it to be accessible outside also.
2 Comments
load callback function unless you declare values outside.
valuesis arrayvar values ={ odds_base :10, start_cash : 50 }console.log(odds_base)