javascript中缺少值(未定义)

时间:2014-02-28 06:10:06

标签: javascript undefined keyvaluepair object-properties

我有关键值&的对象列表当我将它们分开以显示特定字段的每个信息时。 我收到类型错误 data.validation [i] .user 未定义 但是我已经检查过已经赋值的变量。

var data = {validation:[
{"user":"user may not be empty"},
{"date":"Date may not be null"},
{"mobile":"passengerMobile may not be empty"},
{"mobileSize":"passengerMobile size must be greater than 11"},
{"name":"passengerName may not be empty"},
{"nameSize":"passengerName size must be between 2 and 30"},
 ]};

var size = data.validation.length;

for(var i =0;i<=size;i++){
if(data.validation[i].user){
 $("#username").html("<p>"+data.validation[i].user+"</p>");
  }
  if($("#mobile").val().length == 0){
    $("#mobilesize").html("<p>"+data.validation[i].mobile+"</p>");
    }
    else if($("#mobile").val().length >= 1){
    $("#mobilesize").html("<p>"+data.validation[i].mobilesize+"</p>");
    }
  }

$(“#mobile”)表示输入字段Id

任何想法都热烈欢迎

3 个答案:

答案 0 :(得分:2)

此处仅使用少于巡回条件。因为它从0,1,2开始形成......

for(var i =0;i<size;i++)

你的长度是6,但是当最后一次取,那么这应该是

data.validation[5].user

你正确的代码应该是:

  var size = data.validation.length;

    for(var i =0;i<size;i++){
    if(data.validation[i].user){
     $("#username").html("<p>"+data.validation[i].user+"</p>");
      }
      if($("#mobile").val().length == 0){
        $("#mobilesize").html("<p>"+data.validation[i].mobile+"</p>");
        }
        else if($("#mobile").val().length >= 1){
        $("#mobilesize").html("<p>"+data.validation[i].mobilesize+"</p>");
        }
      }

答案 1 :(得分:1)

检查阵列结构:

var data = {validation:[
{"user":"user may not be empty"},
{"date":"Date may not be null"},
{"mobile":"passengerMobile may not be empty"},
{"mobileSize":"passengerMobile size must be greater than 11"},
{"name":"passengerName may not be empty"},
{"nameSize":"passengerName size must be between 2 and 30"},
 ]};

这就像(伪代码):

data = object
data.validation = array
data.validation[0] = object
data.validation[0].user = "user may not be empty"
data.validation[1].user = undefined!!
data.validation[2].user = undefined!!
data.validation[3].user = undefined!!

所以你必须改变你的结构..

答案 2 :(得分:0)

对于验证中的某些值,您没有“user”,因此您未定义。

请使用此代码以避免此类问题:

if(typeof data.validation[i].user != "undefined" && data.validation[i].user){
    $("#username").html("<p>"+data.validation[i].user+"</p>");
 }