0

If I have:

var red = ["#F33121", "#F06562", "#90A4AE"]; //my array called red.
var blue = ["#345678", "#234423", "#435223"]; //my array called blue.
var color = $('.element').text(); // = red

So now, console.log(color); returns red.

How can I get

console.log(color[0]) to return the contents of red[0]?

Sorry if it doesn't make sense, I can't think of a simpler way to put it.

3 Answers 3

2

Bad practice:

If the arrays are global variables you can use bracket notation with window object to access the array.

window[color][0]

var red = ["#F33121", "#F06562", "#90A4AE"]; //my array called red.
var blue = ["#345678", "#234423", "#435223"]; //my array called blue.


$('input').on('keyup', function() {
  var color = $.trim($(this).val());

  $('pre').html(window[color] ? JSON.stringify(window[color], 0, 4) : 'No color found');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" />

<pre></pre>

Better alternative:

Use the object to store the key-value pair as follow:

var colors = {
    red: ["#F33121", "#F06562", "#90A4AE"],
    blue: ["#345678", "#234423", "#435223"]
};

and access the array using

colors[color]

var colors = {
  red: ["#F33121", "#F06562", "#90A4AE"],
  blue: ["#345678", "#234423", "#435223"]
};

$('input').on('keyup', function() {
  var color = $.trim($(this).val());
  $('pre').html(colors[color] ? JSON.stringify(colors[color], 0, 4) : 'No color found');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" />

<pre></pre>

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

Comments

0

Change your code to be an object and you can just use bracket notation

var colors = { 
    red : ["#F33121", "#F06562", "#90A4AE"], 
    blue : ["#345678", "#234423", "#435223"]
};
var color = $('.element').text(); 
console.log(colors[color]);

Comments

0

If provided code is under the global context(window), you can access property of the window object using [] notation.

I suggest you to have object of arrays like var obj = {red:[...],blue:[...] } so that you can easily access the key of the object.

Try this:

var red = ["#F33121", "#F06562", "#90A4AE"];
var blue = ["#345678", "#234423", "#435223"];
var color = 'red'
console.log(window[color][0]);//will not work if variables are local and do not belong to `window`

Using object:

(function() {
  var input = {
    red: ["#F33121", "#F06562", "#90A4AE"],
    blue: ["#345678", "#234423", "#435223"]
  }
  var color = 'red'
  console.log(input[color][0]);
})();

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.