无法理解此更新功能的流程

时间:2016-07-15 15:52:44

标签: javascript function object if-statement

好的,我有一个记录集合对象:

var collection = {
    "2548": {
      "album": "Slippery When Wet",
      "artist": "Bon Jovi",
      "tracks": [ 
        "Let It Rock", 
        "You Give Love a Bad Name" 
      ]
    },
    "2468": {
      "album": "1999",
      "artist": "Prince",
      "tracks": [ 
        "1999", 
        "Little Red Corvette" 
      ]
    },
    "1245": {
      "artist": "Robert Palmer",
      "tracks": [ ]
    },
    "5439": {
      "album": "ABBA Gold"
    }
};

代码已更新,具有以下功能:

function updateRecords(id, prop, value){
   if (prop === "tracks" && value !== "") {
   if(collection[id][prop]) {
    collection[id][prop].push(value);
   }
   else {
    collection[id][prop]=[value];
   }
  } else if (value !== "") {
    collection[id][prop] = value;
  } else {
    delete collection[id][prop];
  }

  return collection;

}

我正在寻找有关上述代码段如何运作的一些说明。我把它看作是:

if (prop === "tracks" && value !== "") {
   if(collection[id][prop]) {
    collection[id][prop].push(value);
   }

如果'prop'等于track并且该值不为空,则进入该函数的更新部分。下一部分,我不确定,似乎说'如果集合的id和prop有价值,将id和prop推入集合中。

下一部分我肯定有点失落:

else {
    collection[id][prop]=[value];
   }

从上面开始,我不清楚这个else语句的目的是仅仅验证信息是否已经包含在数组中。

else if (value !== "") {
    collection[id][prop] = value;
  } else {
    delete collection[id][prop];
  }

最后,上面似乎测试的是,该值是否为空白,如果不是,则将该值插入数组中。如果所有条件都失败,则id和prop不会添加到数组中。我不觉得我已经离开这个了,但如果有人能帮助澄清一些混乱,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

首先我解释一下,这是如何运作的:

collection[id][prop]

你有这样一个对象:

var collection = {
  "ID_1": {
    "PROPERTY_A": "AAA"
  }
}

要访问PROPERTY_A

中属性ID_1下的对象collection内部

你可以这样做:

collection["ID_1"]["PROPERTY_A"] // -> "AAA"

您也可以像这样设置值

collection["ID_1"]["PROPERTY_A"] = "AAAAAAAAAAAAAAA"

好的,让我们检查代码:

// if the prop is "tracks", it should be an array, there are many tracks... 
// so it should be handled like an array
if (prop === "tracks" && value !== "") {

   // does "tracks" exists for this item?
   if(collection[id][prop]) {

    // yes.. then push it into the array
    collection[id][prop].push(value);

   } else {
   // otherwise, (when "tracks" does not exist)
   // create the array and put the value as first item

     collection[id][prop] = [value];
   }

上面的代码可以简化为:

// so it should be handled like an array
if (prop === "tracks" && value !== "") {
  // set it to the same value, if the value is not falsey (null, 0, undefined) or make it to an array..
  collection[id][prop] = collection[id][prop] || [];      
  // push the value to it
  collection[id][prop].push(value)

接下来的事情:

// prop is not "tracks", but could be an empty string "", check it
else if (value !== "") {
    // Ok, the value is not an empty string
    // set the value to the prop
    collection[id][prop] = value;
} else {
    // If this is an empty string == "", then delete this property
    delete collection[id][prop]; 
}

尝试理解它,这是非常基础的,如果您有特殊问题,请尽可能准确地进行。