Node.js The problem with the array.

array.length returns 0 always .... Its return is 0 even some element is added to 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
+4
source share
3 answers

Javascript has no associative arrays, makes it an 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']);
+2
source

Array.lengthonly counts values ​​whose key is numeric. You use strings as keys, so your length is always 0. Although this is legal (since arrays are objects), it is confusing and unsuitable for an array.

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

+3
var error = function(){};
error.prototype.test=[1,2,3];  //1,2,3 only example
console.log(new error().test.length);

JavaScript.prototype

, , ( prototype property of error , test.

0
source

All Articles