【问题标题】:How can i remove udefind while im uisng forloop使用 for 循环时如何删除未定义
【发布时间】:2019-03-18 07:49:01
【问题描述】:

当我绑定值时,我得到的值是 undefinedAnil Singh1,Sunil Singh2,Sushil3,Aradhya4,Reena5,我怎样才能删除 undefind

$scope.GetData = function () {
        for (var i = 0; i <$scope.employee.length; i++) {
            var abc = $scope.employee[i];
            angular.forEach(abc, function (value, key) {               
                if (key == "name") 
                    {
                        if ($scope.emailNames != "undefined") {

                     $scope.emailNames = $scope.emailNames + value + ",";
                            console.log($scope.emailNames);
                        }
                    }
            })

【问题讨论】:

  • 为什么减号是他们的错

标签: javascript jquery arrays angularjs


【解决方案1】:

我认为您的问题是您正在寻找字符串比较,但 undefined in Javascript 不是字符串。

这意味着你的支票:

if ($scope.emailNames != "undefined")

通过,然后将 $scope.emailNames 与一个新字符串连接起来,并将 undefined 值转换为历史字符串版本:"undefined" em> 在控制台输出中找到。

为了演示,试试这个代码:

var x;
var y = x + "some new string";
console.log(y);

你得到了:

未定义一些新字符串

要解决问题,您需要修复 if 语句:

if ($scope.emailNames !== undefined)

请注意我使用 !== 来检查 $scope.emailNames 是否也是相同的类型。

这意味着如果你有一个 null 它将再次失败,你会在你的日志中找到 nullsome new string

在这种情况下,只需使用只有 1 个相等的 !=,将 null 值视为 undefined

【讨论】:

    【解决方案2】:

    我认为您需要检查未定义而不是“未定义”

    【讨论】:

      【解决方案3】:

      使用 .substring() 方法,如下所示

       $scope.GetData = function () {
              for (var i = 0; i <$scope.employee.length; i++) {
                  var abc = $scope.employee[i];
                  angular.forEach(abc, function (value, key) {               
                      if (key == "name") 
                          {
                              if ($scope.emailNames != "undefined") {
                                  $scope.emailNames = $scope.emailNames + value + ",";
                                  var res = $scope.emailNames.substring(9);
                                  console.log(res);
                              }
      
      
        }
              })
      

      【讨论】:

        猜你喜欢
        • 2018-05-22
        • 1970-01-01
        • 2016-11-20
        • 1970-01-01
        • 1970-01-01
        • 2011-09-23
        • 2016-04-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多