javascript node.js Array.length 问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20114606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
node.js Array.length issue
提问by balaphp
array.length is returning 0 always.... Its returning 0 even some item added into the array...
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
采纳答案by Sudhir Bastakoti
Javascript does not have associative arrays, make it object like:
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']);
回答by user949300
Array.length
only counts values whose key is numeric. You are using stringsas 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.
Array.length
只计算键为numeric 的值。你使用字符串作为键,所以你的长度总是 0。虽然合法,(因为数组是对象)这很混乱,不适合数组。
As @Sudhir suggests, use an "object" or "hash" : the { } notation. Much clearer. (Though I disagree with him modifying with the Object.prototype)
正如@Sudhir 所建议的那样,使用“对象”或“哈希”:{} 表示法。清楚多了。(虽然我不同意他用 Object.prototype 修改)
回答by Prateek
var error = function(){};
error.prototype.test=[1,2,3]; //1,2,3 only example
console.log(new error().test.length);
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.
但是使用此函数创建的对象将在其原型链中具有此属性(prototype property
从error
指向已test
定义属性的对象开始。