1

Using Javascript, I need to create a matrix table that looks like the matrix below:

0 1 1 1
1 0 1 1
1 1 0 1
1 1 1 0

The following code, to me, seems like that should be correct, however when I try to output arr[0][1] etc... no value show. Did I do something wrong in the following code:

var address = [
"...",
"....",
".....",
"......"

];

var arr = [];

for (i = 0; i < address.length; i++) 
{ 
    for (j = 0; j < address.length; j++) 
    { 
        //alert(i + " " + j);
        if (i=j)
        {
            arr[i][j]=0;
        }
        else
        {
            arr[i][j]=1;
        }
    }
}
3
  • 3
    i=j is assigning the value of j to i. If you want to compare, then you need to do i === j Commented Apr 28, 2015 at 2:44
  • Mind if I ask, what's the point of using address.length instead of just 4? Commented Apr 28, 2015 at 2:48
  • dman, this is just a test, eventually I will have more than 25. It is still not working: jsfiddle.net/anna5xp6/1 Commented Apr 28, 2015 at 2:50

1 Answer 1

3

You have 2 problems in your script

for (i = 0; i < address.length; i++) {
    //need to initialize arr[i] else `arr[i]` will return undefined
    arr[i]= [];
    for (j = 0; j < address.length; j++) {
        //need == not =
        if (i == j) {
            arr[i][j] = 0;
        } else {
            arr[i][j] = 1;
        }
    }
}

console.log(arr)

Where the if..else can be replaced by a ternary operator

for (j = 0; j < address.length; j++) {
    arr[i][j] = i == j ? 0 : 1;
}

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

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.