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

Javascript 当满足循环内部条件时,如何仅显示特定控制台,javascript,html,angularjs,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{

这是我的控制器功能:

$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.");
            }
    }
}
例如,我的$scope.listOfnames中已经有一个“STUART”姓, 当我在姓氏输入栏中输入“STUART”姓氏时, 它必须仅在我的控制台中显示“此姓氏已存在!”


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

您在控制台上得到这个问题,因为“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.");
    }
}
$scope.Save=函数(){
var=false;
//循环遍历数组并检查每个数组。如果找到,请更改找到的var值
对于(变量i=0;i<$scope.listOfnames.length;i++){
if($scope.listOfnames[i]。姓氏==$scope.name.姓氏){
发现=真;
}
}
如果(找到){
log(“此姓氏已存在!”);
}否则{
log(“保存此姓氏”);
}
}
$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.");
    }
}