5

array.length is returning 0 always.... Its returning 0 even some item added into the array...

 function validate () { 

  error = new Array();

  if(req.body.category_id==""){ 
    error['category_id'] = "Please select category";
  }

  if(req.body.text==""){ 
    error['text'] = "Enter the word";
  }

  if(!(req.body.email!="" && req.body.email.test(/@/))){ 
    error['email'] = "Invalid email id";
  }

  if((req.session.number1+req.session.number2)!=req.body.captcha){ 
    error['captcha'] = "Captcha verification failed";
  }  

 console.log(error.length);
 console.log(error['category_id']);

  if(error.length){ 
    return false;   
  }else{ 
    return true;
  }
}

result of the console.log
//0
//Please select category
balaphp
  • 1,306
  • 5
  • 20
  • 40

3 Answers3

3

Array.length only counts values whose key is numeric. You are using strings as the keys, so your length is always 0. Though legal, (since Arrays are Objects) this is confusing and isn't a good fit for an array.

As @Sudhir suggests, use an "object" or "hash" : the { } notation. Much clearer. (Though I disagree with him modifying with the Object.prototype)

user949300
  • 15,364
  • 7
  • 35
  • 66
2

Javascript does not have associative arrays, make it object like:

//function to get size of object
Object.prototype.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};
var error = {}; //object
if(req.body.category_id==""){ 
    error['category_id'] = "Please select category";
}
...
//rest of your code
if( Object.size(error) ){ //check if we have error
    return false;   
}else{ 
    return true;
}

//check the size of object
console.log(  Object.size(error) );
console.log(error['category_id']);
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
  • 4
    `return Object.keys(obj).length`? – robertklep Nov 21 '13 at 07:31
  • 1
    Never, ever modify objects you don't own. This goes double for built-in objects like Array or Object. Haven't we learned anything from prototype.js? – slebetman Nov 21 '13 at 08:21
  • -1 Object.keys(error).length would be far superior: it does the same thing using a built in function and without modifying Object.prototype. – user949300 Nov 17 '14 at 16:30
0
var error = function(){};
error.prototype.test=[1,2,3];  //1,2,3 only example
console.log(new error().test.length);

Use JavaScript.prototype

But objects created with this function will have this property in their prototype chain (as prototype property of error points to the object that has test property defined.

Community
  • 1
  • 1
Prateek
  • 6,785
  • 2
  • 24
  • 37