1

我有具有键值和对的对象列表。当我将它们分开以在特定字段上显示每个信息时。我收到类型错误data.validation[i].user is undefined 但我检查了变量是否已分配值。

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

欢迎任何想法

4

3 回答 3

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>");
        }
      }
于 2014-02-28T06:13:33.477 回答
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!!

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

于 2014-02-28T06:13:44.527 回答
0

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

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

if(typeof data.validation[i].user != "undefined" && data.validation[i].user){
    $("#username").html("<p>"+data.validation[i].user+"</p>");
 }
于 2014-02-28T06:14:24.497 回答