0

Hello I am creating a two dimensional array in javascript. the object looks like this.

totalCells = [
    lineNumber = 0,
    cells = []
 ];

How do I add that to this array ?

Can I do totalCells.push(1, ['a', 'b', 'c']);

But this throws me the error : cells is not defined

1
  • 1
    You seem to be confusing arrays and objects. In JS, arrays have numbered elements, object have named properties. Commented Jun 19, 2014 at 7:01

3 Answers 3

3

You can't do what you're trying. If you want keys in an array use an object. Then you can do this:

var totalCells = {
    lineNumber: 0,
    cells: []
};

// some logic...

totalCells.lineNumber = 1;
totalCells.cells = ['a', 'b', 'c'];

Alternatively, you could have an array of objects which ties the cells directly to multiple lineNumbers:

var totalCells = [];

// some logic...

totalCells.push({
    lineNumber: 1,
    cells: ['a', 'b', 'c']
});

totalCells.push({
    lineNumber: 2,
    cells: ['x', 'y', 'z']
});
Sign up to request clarification or add additional context in comments.

2 Comments

= should be : in the object literal.
@Barmar thanks. Copy+paste not always the best way :)
0

A simpler way to model your 2 dimensional array would be to use an array of arrays. e.g.

totalCells = [];

totalCells.push(['a','b','c']);
totalCells.push(['d','e','f']);

The line number is implicit, for example, in this case, totalCells[0] is the first line, etc.

Comments

0

As an alternative to Rory answer. Use an object

var totalCells = {}

Then you can directly add keys/properties:

totalCells[1] = ['a','b','c']
totalCells[2] = ['d','e','f']

The advantage with this is you can use your object as a Map:

totalCells[1] will return ['a','b','c']

Using underscore.js (or lodash), you can then do fancy manipulations like extract keys, etc....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.