Взять indexOf
имени, а не я (индекс)
var mostEvil = {
Cthulhu: "Most evil",
Dracula: "Fairly evil",
Voldermort: "Pretty damn evil",
Sauron: "Ridiculously evil"
};
var orderOfPlanets = ["Mercury", "Venus", "Earth", "Mars"];
function each(input, callback) {
if (Array.isArray(input)) {
for (var i = 0; i < orderOfPlanets.length; i++) {
var name = orderOfPlanets[i];
//var val = orderOfPlanets.indexOf(i);
var val = orderOfPlanets.indexOf(name);
callback(val, name);
}
} else if (typeof input == "object") {
for (var key in input) {
var name = key;
var val = input[key];
callback(val, name);
}
}
}
each(orderOfPlanets, function(val, name) {
console.log("The value of " + name + " is " + val);
});
Так же эффективно возвращается i
var mostEvil = {
Cthulhu: "Most evil",
Dracula: "Fairly evil",
Voldermort: "Pretty damn evil",
Sauron: "Ridiculously evil"
};
var orderOfPlanets = ["Mercury", "Venus", "Earth", "Mars"];
function each(input, callback) {
if (Array.isArray(input)) {
for (var i = 0; i < orderOfPlanets.length; i++) {
var name = orderOfPlanets[i];
//var val = orderOfPlanets.indexOf(i);
var val = i;
callback(val, name);
}
} else if (typeof input == "object") {
for (var key in input) {
var name = key;
var val = input[key];
callback(val, name);
}
}
}
each(orderOfPlanets, function(val, name) {
console.log("The value of " + name + " is " + val);
});