-2

I have a JavaScript map that looks like this

var code = {'as':'','db':'','id3':'','term':''};

And want to print for example as into a div. If I do this, I get 'Undefined' inside the div. As I understand, this means the value itself is undefined. How can I "predefine" the empty string?

Update:

As there seems to be a lot of confusion: If I put code[1] into a div using the code above, the div contains 'Undefined'.

Update:

The markup looks as follows

<div id="cont" class="diff">
    <div id="editor">
        <div id="funcRow">
            <ul>
                <li><a onclick="changeTab(0)">Settings</a></li>
                <li><a onclick="changeTab(1)">Knowledge</a></li>
                <li><a onclick="changeTab(2)">Layer 4</a></li>
                <li><a onclick="changeTab(3)">Hardware</a></li>
            </ul>
        </div>
        <div id="text" contenteditable=true>
        </div>
    </div>
</div>

and changeTab(i) looks as follows:

function changeTab(i) {
    code[activeTab] = document.getElementById("text").innerHTML;
    document.getElementById("text").innerHTML = code[i];
    document.getElementsByTagName("ul")[0].getElementsByTagName("li")[i].getElementsByTagName("a")[0].className="active";
    document.getElementsByTagName("ul")[0].getElementsByTagName("li")[activeTab].getElementsByTagName("a")[0].className="";
    activeTab = i;
}
Jouh
  • 74
  • 8
  • What would empty string be "predefine"d to ? – guest271314 Jan 17 '16 at 15:10
  • Can you add code that will display the value in the `
    `
    – Tushar Jan 17 '16 at 15:11
  • Empty strings don't just magically become `undefined`, you're doing something wrong ? – adeneo Jan 17 '16 at 15:12
  • The current code that defines the innerHTML is document.getElementById("text").innerHTML = code[i]; where i is an integer from 0 to 3 – Jouh Jan 17 '16 at 15:16
  • @Jouh You cannot use index(_you can, but this is not what you want_) on object, use `code.as` or `code['as']` to get the value of key `as`. – Tushar Jan 17 '16 at 15:17
  • @Tushar actually using ff's console trying code[1]; prints a value. Why is it that if JS can't iterate over a map this works? – Jouh Jan 17 '16 at 15:19
  • What is the expected output, add the result markup – Tushar Jan 17 '16 at 15:22
  • 1
    Looks like you should be using an array as you're assuming there will be order, and objects have no order. – adeneo Jan 17 '16 at 15:26
  • I actually want to be able to do both, iterate as using an array and use keys. I just recently tried to get into JavaScript, but am pretty used to Python. I guess I projected too much. – Jouh Jan 17 '16 at 15:27
  • @Jouh See http://stackoverflow.com/help/how-to-ask – guest271314 Jan 17 '16 at 15:28
  • 1
    _"If I do this, I get 'Undefined' inside the div."_ `activeTab` appear `undefined` ? Try defining `activeTab` , initially, outside of `changeTab` ; e.g., `var activeTab = "as"` ; though still passing indexes instead of property names to `changeTab` ? – guest271314 Jan 17 '16 at 15:32
  • 1
    You can use `for (var prop in code) ` to iterate through the keys of a map. BUT, the order the props are returned is not guaranteed. – John Hascall Jan 17 '16 at 15:33
  • Alright, I understand. So there is no easy way too iterate over a map while keeping the order. Thank you – Jouh Jan 17 '16 at 15:41
  • @Jouh There is, but it requires two objects, see my answer... (the 2nd part) – John Hascall Jan 17 '16 at 15:52

4 Answers4

1

The code below should be self-explanatory, just stringify before outputting

var div = document.getElementById('test');

var code = {'as':'','db':'','id3':'','term':''};

div.innerHTML = '<pre>' + JSON.stringify(code, null, 4) + '</pre>';
<div id="test"></div>

If you just want to output one of the values, use the key to access it

var div = document.getElementById('test');

var code = {'as':'1','db':'2','id3':'3','term':'4'};

div.innerHTML = code.as; // dot notation, or "code['as']" for bracket notation
<div id="test"></div>
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • I think you misunderstood me. I want to print the value of 'as' into a div, like div.innerHTML = code['as']; – Jouh Jan 17 '16 at 15:14
  • @Jouh - somewhat deliberately, as you weren't very clear, but I added just getting the values of an object as well – adeneo Jan 17 '16 at 15:25
  • Alright, I'm sorry if my question was inaccurate. I do want to be able to iterate over the array though, but as I understand it iterating is not possible like this and thus creating the described unwanted behaviour. – Jouh Jan 17 '16 at 15:26
  • See also http://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets on the wisdom of `code.as` vs. `code['as']` – John Hascall Jan 17 '16 at 15:27
0

Like this, but since the value is "nothing", the output is "nothing".

var div = document.getElementById('test');

var code = {'as':'','db':'','id3':'','term':''};

// code['as'] = "hello, world";     // un-comment to see something

div.innerHTML = '[' + code['as'] + ']';
<div id="test"></div>

Here is a second idea, based on the revision of your question:

var div = document.getElementById('test');


var keys = ['as', 'db', 'id3', 'term' ];

var code = {};
for (var i = 0; i < keys.length; ++i) code[keys[i]] = '';

code['as'] = "hello, world";
// code[keys[0]] = "hello, world";      // or this
  
div.innerHTML = '[' + code['as'] + ']' + ' (' + code[keys[0]] + ')';
<div id="test">X</div>
John Hascall
  • 9,176
  • 6
  • 48
  • 72
  • Why you need `
    `, remove it.
    – Tushar Jan 17 '16 at 15:19
  • EDIT: Changed to use '[' and ']' to bracket the value, since it is nothing and therefor hard to see that anything happened. – John Hascall Jan 17 '16 at 15:21
  • Yes, this is an answer I forsaw, though I'm currently looking for a way around all this. I mainly wanted to know where that Undefined came from, and I would like to apologize if that was not clear enough. – Jouh Jan 17 '16 at 15:56
  • If you find one, let the rest of the world know... :) – John Hascall Jan 17 '16 at 15:57
0

Try using for..in loop, .innerHTML ; using break to stop loop after as property printed to div

// "predefine" empty strings with `1` , `2, `3`, `4`
var code = {'as':'1','db':'2','id3':'3','term':'4'};

var div = document.querySelector("div");

for (var prop in code) {
  if (prop === "as") {
    div.innerHTML += code[prop];
    break;
  }
}
<div></div>
guest271314
  • 1
  • 15
  • 104
  • 177
  • Why looping over all properties and check if key is `as`. Just use `code.as`. Simple! – Tushar Jan 17 '16 at 15:20
  • @Tushar Well, Question , expected results not entirely clear at onset ? Particularly at _"How can I "predefine" the empty string?"_ – guest271314 Jan 17 '16 at 15:21
  • @guest271314 It's over-complicated for the question at hand, but the `for (var prop in code)` is probably a useful thing for the questioner to learn. – John Hascall Jan 17 '16 at 15:24
  • @JohnHascall Question at hand still not clear , here. Is _"How can I "predefine" the empty string?"_ no longer part of Question ? – guest271314 Jan 17 '16 at 15:26
  • I am assuming he's asking how to put a value in `code['as']` as in the comment in my answer, but I could easily be wrong given the fractured English... – John Hascall Jan 17 '16 at 15:28
  • Shouldn't you ask / tell the person in question what youre telling each other? – Jouh Jan 17 '16 at 15:53
  • Define _here_ please, this is your own answer with zero comments from my side before "_Shouldn't you ask / tell the person in question what youre telling each other?_" – Jouh Jan 17 '16 at 16:02
  • @Jouh "here" is this user . What is requirement ? – guest271314 Jan 17 '16 at 16:02
  • @guest271314 Requirement generally is a word, if I recall my school correctly. – Jouh Jan 17 '16 at 16:03
  • @Jouh _"Requirement generally is a word, if I recall my school correctly."_ ? What is the requirement of the Question asked ? What is the expected result of the Question asked ? These are what is not certain , here; as the Question appears to have changed from _"How can I "predefine" the empty string?"_ , which also, was not immediately clear , here. Why posted `for..in` loop example to iterate all proerties of object – guest271314 Jan 17 '16 at 16:04
  • There is no requirement for the question, and the expected result is an answer to my question. If unclear, look at my answer, which should explain everything. Please keep in mind that your sidetalk with another person is not constructive if you do not comprehend the question. – Jouh Jan 17 '16 at 16:06
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/100898/discussion-between-guest271314-and-jouh). – guest271314 Jan 17 '16 at 16:07
0

The problem was me trying to call code[i], which is not possible in JavaScript. Undefined popped up because JS tried to evaluate the value to the key, which was not present at first.

Jouh
  • 74
  • 8