I am trying to alert the values in each conditional of a loop below (in the function returnFunction). I have a function myFunction that is structured as so:
var myFunction = function () {
window.myArray = {
1: returnFunction("a"),
2: returnFunction("b"),
3: returnFunction("c"),
4: returnFunction("d"),
5: returnFunction("e"),
6: returnFunction("f"),
7: returnFunction("g")
}
}
returnFunction looks like this:
var returnFunction = function (classID) {
var myArray = [], tempcounter = 0;
tempcounter = document.getElementsByClassName(classID).length;
myArray = {classID : tempcounter};
return alert(myArray[0] + ' ' + myArray[1]);
}
The returned value that is alerted is undefined undefined
It's my understanding the flow here is that when myFunction is called, it calls returnFunction 7 times, each time sending a different string ("a" through "g") that represent a specific class in the DOM. For a given class "a" through "g", the number of instances of the class (classID) is then counted and returns the classID and a number, which should be returned in the alert.
Can anyone tell me where I am going wrong here?
This code is something of a mess, so I'll try to clean it up.
Assuming the point of this function is to capture the current length for all objects on the page, this is a bit clearer:
var classArr = ['a','b','c','d','e','f','g'],
lengthObj = {},
getLength = function(classID){
return document.getElementsByClassname(classID).length;
},
lengthFunc = function(){
for(var i = classArr.length; i--;){
lengthObj[i+1] = {
classArr[i]:getLength(classArr[i])
};
}
}
lengthFunc();
This does the following:
By the way, it made no sense whatsoever to return an alert
to a value of an object (or array, either one), but it made way more sense to assign the object of classID:length
to each value. Last note is that I would make the lengthFunc
0-indexed instead of 1-indexed, but I kept it the same as you had it, hence the [i+1]
.