0

I am working on this demo. How I can Concatenate the years.range with counter to have years.range2[0]?

let years = {
  range1: [200, 2001, 2002, 2003],
  range2: [2004, 2005, 206, 2007]
}

//$('#year').html(years.range1[0]);
let counter = 1;
$('#year').html(years.range + counter + [0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="year"></div>

2
  • what the result you are looking for? Commented Nov 13, 2018 at 20:27
  • range is an array so you can index on it, try it like this years.range[counter] Commented Nov 13, 2018 at 20:30

2 Answers 2

1

Try this to access the range2 item from the years range object:

let years = {
  range1: [200, 2001, 2002, 2003],
  range2: [2004, 2005, 206, 2007]
}

const counter = 2  // <--- gets you `years['range2']` when concatenated

$('#year').html(years[`range${counter}`][0]); 

By you doing this: $('#year').html(years.range + counter + [0]);

the issue is that years.range + counter would give you the proper array index but +[0] would mess things up since you are saying add years.range1 with an array containing single element - 0.

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

Comments

1

Dynamic property access requires [ ... ] :

 years["range" + counter][0]

But why is years not an array? That would make the while thing way easier.

 const years = [
    [200,2001,2002,2003],
[2004,2005,206,2007]
];

console.log(years[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.