我能写得更简单吗?

时间:2018-04-09 05:15:02

标签: javascript

这是对freecodecamp.com的测试,我只是想知道我是否可以写这个更简单或者如果可以的话?

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

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

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

  return collection;
}

updateRecords(2468, "tracks", "Free");

2 个答案:

答案 0 :(得分:0)

请选中props === 'tracks' only once

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

答案 1 :(得分:0)

是的,您可以将其简化为三个if/elseif/else块,如下所示:

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

    return collection;
}