Jamus
Jamus

Reputation: 865

Array within an array

I believe that what I'm trying to do is declare several arrays within an array. In a text document, I have the following:

"一","いち","one"
"二","に","two"
"三","さん","three"
"四","し・よん","four"
"五","ご","five"

Which I want to automatically place into an array with the items assigned as groups of 3, so for instance set_one[0][1] would be "いち", set_one[3][2] would be "four", so on.

For the life of me, I cannot figure out how to even read the values line by line from the plain text document, let alone try to automatically assign them into arrays.. so I tried manually. I have:

var set_one = new Array(new Array("一", "いち","one"), new Array("二", "に","two", new Array("三", "さん","three", new Array("四", "よん・し","four", new Array("五", "ご","five");

Which, when document.write(set_one[3][2]); is called, nothing happens what-so-ever.. I even tried a for loop to see if anything exists in the (set_one) array at all, though as far as I can tell, nothing does.

It's difficult working on this windows machine to say the least, as I have no debugging tools available, and it doesn't have an active Internet connection! What am I doing wrong? Is there a better way of doing this? Is it even possible to read the values into an array automatically line-by-line, then assign the values to individual arrays based on the comma values?

Upvotes: 0

Views: 237

Answers (2)

João Silva
João Silva

Reputation: 91299

You're not creating the array correctly. For example, when you have:

new Array("二", "に","two", new Array("三", "さん","three"))

You are actually creating a single-element array, in which the 3rd position is itself another array. Either use:

new Array (new Array("二", "に","two"), new Array("三", "さん","three"))

Or the much simpler, and less confusing way of creating arrays in JavaScript:

var set_one = [ 
  [ "一","いち","one" ],
  [ "二","に","two" ],
  [ "三","さん","three" ],
  [ "四","し・よん","four" ],
  [ "五","ご","five" ] 
];
set_one[0][1]; // いち

Upvotes: 3

Doug Domeny
Doug Domeny

Reputation: 4470

var set_one = [
["一","いち","one"], 
["二","に","two"], 
["三","さん","three"], 
["四","し・よん","four"], 
["五","ご","five"]
];

Upvotes: 0

Related Questions