2014-10-06 57 views
0

我需要根据if语句的结果向数组添加错误消息。下面的代码仅在我输入应触发两者的数据时才会返回第二条错误消息。我知道.push()不只是添加到前一个数组,而是他们必须解决的唯一方法是创建一个for循环。我觉得有一些简单的功能在某处,我只是想念。根据if语句添加到Javascript数组

$scope.error = {}; 
    if ($password == null || $vPassword == null || $email == null || $vEmail == null) { 
     console.log('All fields must be filled in'); 
    } else { 
     if ($scope.verifyPassword !== $scope.password) { 
      $scope.error[scope.error.length()] = 'Your passwords must match...'; 
     } 
     if ($scope.verifyEmail !== $scope.email) { 
      $scope.error.push = ['Your email addresses must match...']; 
     } 
     console.log($scope.error); 
    } 

我认为这个代码很好理解。让我知道你是否需要更多信息。

谢谢!

编辑:我不知道什么代码产生了我解释的错误。抱歉。上面的代码是糟糕的代码,我试图让它工作。很显然,其中大部分都没有意义。被接受的答案是我原本认为会产生这个错误,但显然它起作用。对不起,这个蹩脚的帖子。

+0

对于数组:'$ scope.error = []';那么只需'.push(“字符串”)'根据需要 – 2014-10-06 16:12:19

回答

3

push是一个函数,应该使用()来调用。

$scope.error.push('Your email addresses must match...'); 

此外,您不能在不是Array的对象上调用push。你必须初始化$scope.error作为Array

$scope.error = []; 
+0

我不像我的问题一样愚蠢让我看起来。阅读我编辑的问题。虽然谢谢!有用! – 2014-10-06 16:22:14

0

您需要更改$scope.error到一个数组,而不是一个对象,然后将.push()适当工作。

$scope.error = []; 
$scope.error.push("Your passwords must match..."); 

console.log($scope.error); 

可生产

["Your passwords must match..."]