我需要根据 if 语句的结果将错误消息添加到数组中。仅当我输入应触发这两个错误消息的数据时,下面的代码才会返回第二条错误消息。我知道 .push() 不仅仅添加到前一个数组中,而且他们必须解决这个问题的唯一方法是创建一个 for 循环。我认为我缺少一些简单的功能。
$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);
}
我认为代码是非常不言自明的。如果您需要更多信息,请告诉我。
谢谢!
编辑:我不确定是什么代码产生了我解释的错误。对不起。上面的代码是我为了让它工作而搞乱的垃圾代码。显然大部分都是没有意义的。接受的答案是我最初认为产生该错误的答案,但显然它有效。抱歉,这篇文章很糟糕。
最佳答案
push
是一个函数,应使用 ()
调用。
$scope.error.push('Your email addresses must match...');
此外,您无法对非数组的对象调用 push
。您必须将 $scope.error
实例化为 Array
:
$scope.error = [];
关于javascript - 根据 if 语句添加到 Javascript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26220315/