【问题标题】:JavaScript Empty Array indexOfJavaScript 空数组 indexOf
【发布时间】:2015-09-26 06:26:04
【问题描述】:

我昨天浏览了一些JS代码,但我无法理解。这是代码

var data = {
     name : 'Mr John',
     age : '29',
     location : 'New York',
     profession : 'Accoutant'
};

var allowedNull = [];

for (var i in data) {
     if (!data[i])
     {

          if (allowedNull.indexOf(i) < 0)
          {
               console.log('Empty');
          }
     }
}

如果data 具有空属性,则脚本实际上会在控制台中打印“Empty”。我只是想知道,它是如何通过在 allowedNull 上调用 indexOf 来工作的。有人能解释一下这是如何工作的吗?

小提琴:Check

【问题讨论】:

    标签: javascript arrays object indexof


    【解决方案1】:

    首先indexOf(i) 方法返回可以在数组中找到给定元素的第一个索引,如果不存在则返回-1。 在这种情况下,流程是:

    //loop over data object
    
    for (var i in data) {
    
    //if the current property is empty/undefined
     if (!data[i])
     {
          //and if this property is not present inside the allowedNull array
          if (allowedNull.indexOf(i) < 0)
          {
               // print empty
               console.log('Empty');
          }
     }
    }
    

    如果您尝试在数据对象中添加属性test : '',您将在控制台中打印Empty,但如果您在allowedNull 数组var allowedNull = ['test'] 中添加test,则不会打印任何内容。

    希望这能有所帮助! :)

    【讨论】:

    • 实际上我的代码中不需要 allowedNull ,因为它是空的并且没有被使用。一些误解。 :|无论如何感谢您的帮助;)
    猜你喜欢
    • 1970-01-01
    • 2014-09-16
    • 2012-01-08
    • 1970-01-01
    • 2017-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-22
    相关资源
    最近更新 更多