0

Let's say I have a bunch of arrays named a=[], b=[], c=[], d=[], and so on. A Table is shown to the client and depending on the cell that the client clicks, we do operations to the specific array made for that cell. The code explains what I mean in a better way. I would be thankful if anyone helps. HTML:

<td id="block1" class="blocks" onclick="markNLock('a',this)" onmouseover="setMouseOverColor(this)" onmouseout="setMouseOutColor(this)">

Js:

function markNLock(idx, mark) {
    for(var i=0; i<Matrix.length; i++)
    {
        Matrix[i] += idx[i];
        console.log(idx[i]);
    }
}
11
  • your problems are caused by using mid 90's style inline event handlers. If you write your code using addEventListener instead this problem won't happen. Commented Oct 12, 2020 at 16:05
  • Try telling what exactly is the problem and Half the stuff is not told Commented Oct 12, 2020 at 16:06
  • @AlphaWolfGamer the problem is obvious - the OP is passing a string for the array name, and wants to access the array of that particular name. Commented Oct 12, 2020 at 16:08
  • Why don't you remove the string tag and instead pass in a instead of "a". Problem solved Commented Oct 12, 2020 at 16:10
  • 1
    NB: having a bunch of arrays of (presumed) identical purpose but with different names is an indication of poor design. Variable names are not the way to differentiate items like that - they should either be a two-D array, or an object where the keys are the "identifier" and the array is the value. Commented Oct 12, 2020 at 16:10

1 Answer 1

1

Notwithstanding the other advice I've given, the most expedient fix for your problem is not to use separate arrays, but to use your strings a, b etc as keys into the lookup matrix:

const game_matrix = {
  'a': [1, 1, 0, 0, 1, 0, 0, 0],
  'b': [0, 1, 0, 0, 0, 1, 0, 0],
  ...
}

and you can then use your string parameter as an index into that object:

Matrix[i] += game_matrix[idx][i];
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.