计算文本框中的字数时的意外值

Unexpected value when counting the number of words in a textbox

本文关键字:意外 计算 文本      更新时间:2023-09-26
$scope.cal = function (){
    var totalItems = stringSplit($scope.eatables);
    $scope.value = totalItems;
    if(totalItems == 0){
        $scope.message = "Please enter something";
    }else if(totalItems <= 3){
        $scope.message = "Enjoy!";
    }else{
        $scope.message = "TOO MUCH!";
    }
};
function stringSplit(string){
    var array = string.split(" ");
    var x = array.length;
    return x;
};

我在ng-click上调用这个函数,但是当输入框为空时,它仍然给出1的值。为什么呢?

这个怎么样?

function stringSplit(string){
    var array = string.split(" ");
    var x = array.length;
    return (array[i] === "" || array[i] === null || array[i] === undefined) ? 0 : x;  //Check whether first element is empty
};

发生这种情况是因为模型值是"(空字符串)它不是未定义的如果你试图分割它它将是长度为1的数组,第一个值是"字符串"字符串。分割(' ')["]

所以要在分割它之前修复这个问题你可以检查是否有某个值然后只分割

像这样修改你的函数

function stringSplit(string){
var x
if(string){
var array = string.split(" ");
 x = array.length;
alert(string)
alert(x)
return x;
}else {
x =0
return x
}
};

这里是工作代码笔样例http://codepen.io/vkvicky-vasudev/pen/XjkZBN