bender850
bender850

Reputation: 37

How to define a var in an array?

Building my first real app with JS: Black Jack. I was just wondering why my j, q, k, and a var are coming back as undefined.

window.onload = init;
var cards = [2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10,j,j,j,j,q,q,q,q,k,k,k,k,a,a,a,a];
var j = 10;
var q = 10;
var k = 10;
var a = 11;
function init() {
    var button = document.getElementById("doIt");
    button.onclick = processIt;
}
function processIt() {
    var cpu1 = document.getElementById("cpu1");
    cpu1.innerHTML = cards[37];
}

Any help would be greatly appreciated.

Upvotes: 1

Views: 190

Answers (3)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230561

Because at the moment when you declare cards, those variables (or, rather, their values) are still undefined. Reorder the declarations.

var j = 10;
var q = 10;
var k = 10;
var a = 11;
var cards = [2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10,j,j,j,j,q,q,q,q,k,k,k,k,a,a,a,a];

Upvotes: 4

RobG
RobG

Reputation: 147553

In javascript, declarations are processed first but assignment occurs in order. Your code is effectively:

var cards, j, q, k, a;

// Here, all variables exist but none have a value
// When cards is assigned an array, the values of j, q, k and a 
// are still undefined.
cards = [2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7,8,8,8,
         8,9,9,9,9,10,10,10,10,j,j,j,j,q,q,q,q,k,k,k,k,a,a,a,a];

// Now the rest are given values
j = 10;
q = 10;
k = 10;
a = 11;

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324840

You're defining them after you use them... You have to define variables before you use them, not after.

Upvotes: 3

Related Questions