简体   繁体   中英

node.js Array.length issue

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

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)

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']);
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM