当我的条件内部循环满足时,如何仅显示特定控制台

时间:2018-02-09 06:27:35

标签: javascript html angularjs

这是我的控制器功能:

$scope.Save = function () {

    for(var i = 0; i < $scope.listOfnames.length; i++){
         if($scope.listOfnames[i].surname == $scope.name.surname){
            console.log("This surname is already exist!");

        }else{
            console.log("save this surname.");
            }
    }
}

这是我在控制台的输出:

save this surname.

This surname is already exist!

save this surname.

例如,我在$ scope.listOfnames中已经有一个“STUART”SURNAME, 当我在我的SURNAME INPUT FIELD中输入“STUART”SURNAME时, 它必须显示“这个姓氏已经存在!”只在我的控制台。

我知道我的循环问题,我该怎么办?

1 个答案:

答案 0 :(得分:2)

你在控制台上得到它,因为“STUART”是你阵列上的第二个值。你可以这样做:

$scope.Save = function () {
    var found  = false;

    //Loop thru the array and check each. If found change the value of var found
    for(var i = 0; i < $scope.listOfnames.length; i++){
        if( $scope.listOfnames[i].surname == $scope.name.surname ){
              found = true;
        }
    }


    if ( found ) {
        console.log("This surname is already exist!");
    } else {
        console.log("save this surname.");
    }
}