Caleb Libby
Caleb Libby

Reputation: 132

How can I define an class' array while constructing it?

If you declare an array, you have to assign its elements (or at least acknowledge that it is an array) while declaring it, i.e., var myArray = [1, 2, 3];.

I'm curious as to how one might be able to implement that in an class constructor, for example:

function Matrix(MultiDimensionalArray) {
    this.array = MultiDimensionalArray;
}
var myMatrix = new Matrix() [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

That's the closest thing I could think of to implement this, but I know that it's incorrect. What is the right way to go about this?

Upvotes: 0

Views: 52

Answers (3)

Rajesh
Rajesh

Reputation: 24915

There are many syntactical mistakes in your code.

  1. Function declaration

You can declare functions like:

function functionName(argList) {}

or

var functionName = function(argList){}
  1. Passing arguments

You have to put arguments within parenthesis. So it should be Matrix([...])

  1. Array declaration

Items in an array are separated using commas. You will have to do [ [], [], [] ].

  1. variable names

In the following code:

function Matrix = (MultiDimensionalArray) {
    this.array = multiDimensionalArray;

variable accepted and variable assigned are different. You will have to use the same values.

Sample Code:

function Matrix(multiDimensionalArray) {
    this.array = multiDimensionalArray;
}
var myMatrix = new Matrix([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]);

console.log(myMatrix.array)

Upvotes: 0

ramu
ramu

Reputation: 563

Your constructor call would be like this:

 var myMatrix = new Matrix([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]) 

Upvotes: 4

Vinod Bhavnani
Vinod Bhavnani

Reputation: 2225

var myMatrix = new Matrix([[1,2,3],[4,5,6],[7,8,9]]);

Upvotes: -1

Related Questions