The
for loop is absolutely possible, and it's probably not what the interviewer expected.
because document.getElementsByTagName ('div') gets a class array object, not a real array,
probably want you to convert the class array object into the array object, and then use the array map forEach and other methods
for
loops are OK.
var nodeList = document.getElementsByTagName('div');
for (var i = 0; i < nodeList.length; iPP) {
// code here
console.log(1);
}
the interviewer may prefer you to answer how this is an array object of the array-like-object
class. And then do the cycle.
Plan 1: ES5
Array.prototype.slice.call
var nodeList = document.getElementsByTagName('div'));
var nodeArr = Array.prototype.slice.call(nodeList);
// [].slice.call()
Array.isArray(nodeArr); // true
nodeArr.forEach(() => {
console.log(1);
});
Scheme 2: ES6
extension .
// NodeList
var nodeArr = [...document.querySelectorAll('div')];
nodeArr.forEach(() => {
console.log(1);
});
Plan 3: ES6
Array.from
Array.from(document.querySelectorAll('div')).forEach(() => {
// code here
console.log(1);
});
the interviewer should want you to name the three options of switching to an array. I hope it will be helpful to you ~
calls methods such as getElementsByTagName, document.childNodes, and so on, which return NodeList objects that belong to pseudo arrays. Methods such as loops and push under Array cannot be applied. Convert it to an array before processing:
var domNodes = Array.prototype.slice.call(document.getElementsByTagName("div"));
domNodes.forEach(function(){
//.....
})
The
MDN is also traversed with a for loop. What's wrong with that? MDN