0

How would I assign Cat, dog and Bear it's own value. So it says i.e. Bear = 50. or cat36 ?

HTML:

<p id="item"> </p>
<p id="valueOfItem"> </p>

Javascript:

var items = ["cat","dog","Bear"]

I can't find a single way assign cat, dog and bear a seperate value and then output it.

1
  • Do you want the output to be in HTML? Are you looking for a Javascript answer that generates HTML? Commented Dec 27, 2016 at 21:45

2 Answers 2

3

You may be looking for an object (denoted with curly braces {}), not an array:

var items = {bear: 50, cat: 36, dog: 13};
console.log(items.cat);
//36
Sign up to request clarification or add additional context in comments.

Comments

1

The solution by @nvioli is good, but has the disadvantage that it loses the ordering of the items. Here's a couple of other approaches, both of which preserve the item order. First, an array of objects:

var items = [
    { name: "cat", value: 36 },
    { name: "dog", value: 13 },
    { name: "Bear", value: 50 }
];

The second is parallel arrays:

var items = ["cat","dog","Bear"];
var values = [36, 13, 50];

The latter is more difficult code to write and maintain because related items are stored in separate arrays. But this structure occasionally has its uses.

2 Comments

Of course, if ordering is not important, the other answer is better.
@Barmar - Not necessarily. Iterating through an array is a bit simpler than iterating through all of an object's properties. Plus you automatically get a count of how many items you're dealing with via the array's length property. On the other hand, if you have to look up a value by item name, then the other solution is definitely better.

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.