1

I'm not sure why this outputs undefined for the property names of the document object. I think it has something to do with the variable expression myArray[i++]. I could make this a simple primitive variable and I'll get all the property names, but I would like all the property names saved into an array. Thank you for your help in advance!!

var myArray = [];
var i = 0;
for (myArray[i++] in document) {
document.write(myArray[i] + "</br>");
}
3
  • 3
    Wow, I would have expected for this to throw a syntax error. I really don't encourage to use code like this, but the problem is that at the moment you are accessing myArray[i], the index does not exist yet (i was incremented in myArray[i++]). document.write(myArray[i-1] + "</br>"); works though. Commented Apr 26, 2013 at 0:06
  • This is the syntax for a for/in loop, not a for loop. This should enumerate the properties of the object. If it is invalid, where am I going wrong? Commented Apr 26, 2013 at 0:10
  • 2
    @Dusty, it's just unusual; you usually see an unqualified identifier on the left side of in (just a variable, no brackets or dots). Commented Apr 26, 2013 at 0:17

4 Answers 4

4

That is happening because you are always look one element further in the array than you've defined, since you post-increment i. You could pre-increment instead:

var myArray = [];
var i = -1;
for (myArray[++i] in document) {
    document.write(myArray[i] + "</br>");
}

JSFiddle

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

10 Comments

Nice haha, I was adding the hyphens in post and pre-increment during those 4 seconds lol. I upvoted your answer.
You're welcome @Dusty! I posted a JSFiddle for your convenience, however, it would be awesome to get into the habit of using console.log. It will make writing Javascript a lot easier.
@Dusty The way you had it originally, on the first iteration you are assigning the first property to myArray[0] and then calling document.write(myArray[1]) since i has been incremeneted. If you post-increment in the document.write like Dagg Nabbit did in his answer, you'll also get the correct result.
@Dusty Post increment means that it increments after it's value is returned. i++ increments i and then evaluates to the original value of i.
After the expression x is always incremented, so in any expressions which come afterwards, it doesn't make a difference whether you used preincrement or postincrement, i has been incremented already either way.
|
4

It doesn't work because you increment i after setting myArray[i] by doing myArray[i++] (post increment).

This would work, although I'm not sure why you'd need to do it.

var myArray = [];
var i = 0;
for (myArray[i] in document) {
    console.log(myArray[i++] + "</br>");
}

7 Comments

This won't give all property names.
@yowza I have no idea what you're talking about.
Thanks for the great post! Am I able to see that this code works in jsfiddle... sorry, not to familiar with console.log.
@Dusty most browsers have a console that you can open, usually with the F12 key. console.log just dumps stuff to the console.
F12 in Chrome or IE (I think), or Ctrl-shift-K in FF will open the console for jsfiddle the same as for any other site.
|
1

I think that you may want to use a loop like the one below:

for(int i = 0; i < myArray.length; i++){
  document.write(myArray[i] + "</br>");
}

2 Comments

OP isn't trying to get values from myArray. The goal is to get the names of all the properties of document and store them in the initially empty myArray.
Yup, i gathered that after reading some of the other responses.
1

"I would like all the property names saved into an array. "

You could do:

var names = Object.getOwnPropertyNames(document);

The reason for Object.getOwnPropertyNames() is that it includes non-enumerable properties, whereas for-in will skip them.

But some properties are inherited, so you'd need to do the same on all objects in the prototype chain if that's what you want.

var obj = document;
var names = [];

do {
    names.push.apply(names, Object.getOwnPropertyNames(obj));
} while(obj = Object.getPrototypeOf(obj));

Result in Firefox:

["jQuery17104169501299363202", "location", "addEventListener", "removeEventListener", "dispatchEvent", "getElementsByName", "getItems", "open", "close", "write", "writeln", "execCommand", "queryCommandEnabled", "queryCommandIndeterm", "queryCommandState", "queryCommandSupported", "queryCommandValue", "clear", "getSelection", "captureEvents", "releaseEvents", "routeEvent", "domain", "cookie", "body", "head", "images", "embeds", "plugins", "links", "forms", "scripts", "designMode", "fgColor", "linkColor", "vlinkColor", "alinkColor", "bgColor", "anchors", "applets", "onreadystatechange", "onmouseenter", "onmouseleave", "getElementsByTagName", "getElementsByTagNameNS", "getElementsByClassName", "getElementById", "createElement", "createElementNS", "createDocumentFragment", "createTextNode", "createComment", "createProcessingInstruction", "importNode", "adoptNode", "createEvent", "createRange", "createNodeIterator", "createTreeWalker", "createCDATASection", "createAttribute", "createAttributeNS", "hasFocus", "releaseCapture", "mozSetImageElement", "mozCancelFullScreen", "mozExitPointerLock", "enableStyleSheetsForSet", "elementFromPoint", "querySelector", "querySelectorAll", "getAnonymousNodes", "getAnonymousElementByAttribute", "addBinding", "removeBinding", "getBindingParent", "loadBindingDocument", "createExpression", "createNSResolver", "evaluate", "implementation", "URL", "documentURI", "compatMode", "characterSet", "contentType", "doctype", "documentElement", "inputEncoding", "referrer", "lastModified", "readyState", "title", "dir", "defaultView", "activeElement", "currentScript", "mozFullScreenEnabled", "mozFullScreenElement", "mozFullScreen", "mozPointerLockElement", "hidden", "mozHidden", "visibilityState", "mozVisibilityState", "styleSheets", "selectedStyleSheetSet", "lastStyleSheetSet", "preferredStyleSheetSet", "styleSheetSets", "hasChildNodes", "insertBefore", "appendChild", "replaceChild", "removeChild", "normalize", "cloneNode", "isEqualNode", "compareDocumentPosition", "contains", "lookupPrefix", "lookupNamespaceURI", "isDefaultNamespace", "isSupported", "hasAttributes", "setUserData", "getUserData", "nodeType", "nodeName", "baseURI", "ownerDocument", "parentNode", "parentElement", "childNodes", "firstChild", "lastChild", "previousSibling", "nextSibling", "nodeValue", "textContent", "attributes", "namespaceURI", "prefix", "localName", "lookupGetter", "lookupSetter", "defineGetter", "defineSetter", "QueryInterface", "mozSyntheticDocument", "caretPositionFromPoint", "ELEMENT_NODE", "ATTRIBUTE_NODE", "TEXT_NODE", "CDATA_SECTION_NODE", "ENTITY_REFERENCE_NODE", "ENTITY_NODE", "PROCESSING_INSTRUCTION_NODE", "COMMENT_NODE", "DOCUMENT_NODE", "DOCUMENT_TYPE_NODE", "DOCUMENT_FRAGMENT_NODE", "NOTATION_NODE", "DOCUMENT_POSITION_DISCONNECTED", "DOCUMENT_POSITION_PRECEDING", "DOCUMENT_POSITION_FOLLOWING", "DOCUMENT_POSITION_CONTAINS", "DOCUMENT_POSITION_CONTAINED_BY", "DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC", "location", "onabort", "onblur", "oncanplay", "oncanplaythrough", "onchange", "onclick", "oncontextmenu", "ondblclick", "ondrag", "ondragend", "ondragenter", "ondragleave", "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied", "onended", "onerror", "onfocus", "oninput", "oninvalid", "onkeydown", "onkeypress", "onkeyup", "onload", "onloadeddata", "onloadedmetadata", "onloadstart", "onmousedown", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmozfullscreenchange", "onmozfullscreenerror", "onmozpointerlockchange", "onmozpointerlockerror", "onpause", "onplay", "onplaying", "onprogress", "onratechange", "onreset", "onscroll", "onseeked", "onseeking", "onselect", "onshow", "onstalled", "onsubmit", "onsuspend", "ontimeupdate", "onvolumechange", "onwaiting", "onwheel", "oncopy", "oncut", "onpaste", "onbeforescriptexecute", "onafterscriptexecute", "getElementsByTagName", "getElementsByTagNameNS", "getElementsByClassName", "getElementById", "createElement", "createElementNS", "createDocumentFragment", "createTextNode", "createComment", "createProcessingInstruction", "importNode", "adoptNode", "createEvent", "createRange", "createNodeIterator", "createTreeWalker", "createCDATASection", "createAttribute", "createAttributeNS", "hasFocus", "releaseCapture", "mozSetImageElement", "mozCancelFullScreen", "mozExitPointerLock", "enableStyleSheetsForSet", "elementFromPoint", "querySelector", "querySelectorAll", "getAnonymousNodes", "getAnonymousElementByAttribute", "addBinding", "removeBinding", "getBindingParent", "loadBindingDocument", "createExpression", "createNSResolver", "evaluate", "implementation", "URL", "documentURI", "compatMode", "characterSet", "contentType", "doctype", "documentElement", "inputEncoding", "referrer", "lastModified", "readyState", "title", "dir", "defaultView", "activeElement", "onabort", "onblur", "oncanplay", "oncanplaythrough", "onchange", "onclick", "oncontextmenu", "ondblclick", "ondrag", "ondragend", "ondragenter", "ondragleave", "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied", "onended", "onerror", "onfocus", "oninput", "oninvalid", "onkeydown", "onkeypress", "onkeyup", "onload", "onloadeddata", "onloadedmetadata", "onloadstart", "onmousedown", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onpause", "onplay", "onplaying", "onprogress", "onratechange", "onreset", "onscroll", "onseeked", "onseeking", "onselect", "onshow", "onstalled", "onsubmit", "onsuspend", "ontimeupdate", "onvolumechange", "onwaiting", "onreadystatechange", "onmouseenter", "onmouseleave", "onmozfullscreenchange", "onmozfullscreenerror", "onmozpointerlockchange", "onmozpointerlockerror", "onwheel", "oncopy", "oncut", "onpaste", "onbeforescriptexecute", "onafterscriptexecute", "currentScript", "mozFullScreenEnabled", "mozFullScreenElement", "mozFullScreen", "mozPointerLockElement", "hidden", "mozHidden", "visibilityState", "mozVisibilityState", "styleSheets", "selectedStyleSheetSet", "lastStyleSheetSet", "preferredStyleSheetSet", "styleSheetSets", "constructor", "hasChildNodes", "insertBefore", "appendChild", "replaceChild", "removeChild", "normalize", "cloneNode", "isEqualNode", "compareDocumentPosition", "contains", "lookupPrefix", "lookupNamespaceURI", "isDefaultNamespace", "isSupported", "hasAttributes", "setUserData", "getUserData", "nodeType", "nodeName", "baseURI", "ownerDocument", "parentNode", "parentElement", "childNodes", "firstChild", "lastChild", "previousSibling", "nextSibling", "nodeValue", "textContent", "attributes", "namespaceURI", "prefix", "localName", "ELEMENT_NODE", "ATTRIBUTE_NODE", "TEXT_NODE", "CDATA_SECTION_NODE", "ENTITY_REFERENCE_NODE", "ENTITY_NODE", "PROCESSING_INSTRUCTION_NODE", "COMMENT_NODE", "DOCUMENT_NODE", "DOCUMENT_TYPE_NODE", "DOCUMENT_FRAGMENT_NODE", "NOTATION_NODE", "DOCUMENT_POSITION_DISCONNECTED", "DOCUMENT_POSITION_PRECEDING", "DOCUMENT_POSITION_FOLLOWING", "DOCUMENT_POSITION_CONTAINS", "DOCUMENT_POSITION_CONTAINED_BY", "DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC", "constructor", "addEventListener", "removeEventListener", "dispatchEvent", "constructor", "constructor", "toSource", "toString", "toLocaleString", "valueOf", "watch", "unwatch", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "defineGetter", "defineSetter", "lookupGetter", "lookupSetter"]

12 Comments

Wow... That is a bit unnecessary to show don't you think? Maybe you could post the first few properties of document, followed by a ....
Can you explain this syntax? I trying to output the properties using this code in jsfiddle and I couldn't get it to work.
@yowza How do you know that the OP wants to enumerate non-enumerable properties? Seems counter-intuitive to me.
I can't really speak for the OP, but it seems to me they're asking more about why their for..in loop didn't work as written. (OP states that they can get "all the property names" using other syntax, so even if that isn't "all inheritied and non-enumerable properties" it would seem to be what they want.)
@Dusty: Your loop head was correct, but your loop body was trying to use the same i variable, which had been incremented past the point where the assignment happened. To use it in the body, you'd need to subtract it back out. document.write(myArray[i - 1] + "</br>");
|

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.