Michal McCaskle
Michal McCaskle

Reputation: 1

Uncaught TypeError: Cannot read property '0' of undefined

I have a project to display the 7 largest states in America storing each individual state in a variable and displaying it on the page using javascript.

My NEW code looks like this:

    <script>
var states = ["Alaska", "Texas", "California", "Montana", "New Mexico", "Arizona", "Nevada"];
var miles = [663267, 268581, 163696, 147042, 121589, 113998, 110561];
var index= "";
text="";
function listStates() {
    for (index=0; index < states.length; index++) {
            text += "<tr><td>" + states[index] ;    
            text += "</td><td>" + miles[index] ;
            text += "</td></tr>";
    }
    return text;
}
</script>

And i display it using this one

<section id="table">
<table width="307" height="45">
<tr><th width="40">Name</th><th width="65">Size</th></tr>
<script>
<!--
    var result = listStates();
    document.write(result);
//-->
</script>
</table>

Upvotes: 0

Views: 2385

Answers (2)

Aweary
Aweary

Reputation: 2312

Javascript uses + for string concatenation, not .. You're also re-assigned the text variable at the beginning of each loop, so you're only going to get the last result when it return the last value.

"<tr><td>Nevada</td><td>110561</td></tr>"

Upvotes: 0

Kagami Sascha Rosylight
Kagami Sascha Rosylight

Reputation: 1492

Concatenation in JavaScript uses +, not .. Try +.

Your current code with . will try finding a property named states from a string object, which is undefined. Now the code will find a property named '0' from undefined, and it will fail because undefined cannot have any property.

Upvotes: 1

Related Questions