array.length总是返回0 .... 它返回0甚至一些项目添加到数组中......
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
答案 0 :(得分:3)
Array.length
仅计算键为 numeric 的值。您使用 strings 作为键,因此您的长度始终为0.虽然合法,(因为Arrays是Objects),这很容易混淆,并且不适合数组。
正如@Sudhir建议的那样,使用“对象”或“哈希”:{}表示法。更清楚。 (虽然我不同意他用Object.prototype修改)
答案 1 :(得分:2)
Javascript没有关联数组,使其成为对象:
//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 :(得分:0)
var error = function(){};
error.prototype.test=[1,2,3]; //1,2,3 only example
console.log(new error().test.length);
但是使用此函数创建的对象将在其原型链中具有此属性(prototype property
error
指向已定义test
属性的对象。