I have a function that builds an array with push.
function one(resultsArray) {
activity_basic_weight = 9;
for (i in resultsArray) {
score = 0;
score = resultsArray[i].var_a * activity_basic_weight;
score = Math.round(score * 100) / 100;
if (score >= 80)
{
verygoodCategories1.push({
score: score,
name: i,
url: resultsArray[i].url
});
}
else if (score <= 79)
{
...
}
}
two(verygoodCategories1, ...);
}
function two(verygoodCategories1, ...) {
alert(verygoodCategories1.length); // = 7, correct;
// here comes the problem:
for (var i = 0; i < verygoodCategories1.length; i++) {
//this throws "Error: TypeError: verygoodCategories1 is undefined"
}
}
I am new at Javascript. Am I doing something fundamentally wrong?
This is pseudocode, but I made sure that at least the variable names are correct etc.
Any ideas?
Thanks
J
3 Answers 3
Declaring variables is important. Also, as mentioned in the comments, don't use for...in. Maybe someday you will want to use that but not today.
Here is your pseudo code written so that it could actually work.
var a = [{var_a:100},{var_a:90},{var_a:81},{var_a:81},{var_a:91},{var_a:101}];
function one(resultsArray) {
//This is critical to later using it as an array.
var verygoodCategories1 = [];
// you should always initialize a variable with var.
// You can not do it but thats bad form. You will
// pollute the global space and people will dislike you.
var activity_basic_weight = 9;
for (var i = 0; i < resultsArray.length; i++) {
var score = resultsArray[i].var_a * activity_basic_weight;
score = Math.round(score * 100) / 100;
if (score >= 80)
{
verygoodCategories1.push({
score: score,
name: i,
url: resultsArray[i].url
});
}
else if (score <= 79)
{
//...
}
}
two(verygoodCategories1);
}
function two(verygoodCategories1) {
alert(verygoodCategories1.length); // = 7, correct;
for (var i = 0; i < verygoodCategories1.length; i++) {
//no more errors!
}
}
one(a);
Comments
Assign the array parameter to a variable:
function two(verygoodCategories1, ...) {
alert(verygoodCategories1.length); // = 7, correct;
var goodCategories=verygoodCategories1;
var goodCategoriesLength=goodCategories.length;
for (var i = 0; i < goodCategoriesLength; i++) {
console.log(goodCategories[i]);
}
}
1 Comment
Go to your function one(resultArray). just before the for, you might want to declare the array there like:
verygoodCategories1 = new Array();
2 Comments
verygoodCategories1 as a new array in the location you suggest, it will wipe out the contents each time it loops...
verygoodCategories1as an array? Should be at least averygoodCategories1 = [];in there somewhere.one(...)), not pseudocode? Somevarstatements would be nice there :-)