Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

Refactoring methods in Javascript (adding / deleting items from an array)

I encountered a question where I have to refactor the code below that has several errors in it:

function thingsToBuy() {
  var list = [
    "milk",
    "bread",
    "bananas"
  ];
  return {
    removeItem: function(name) {
      list.filter(item => item === name);
    },
    addItem: function() {
      return list.push();
    },
    getList: function(list) {
      return list;
    }
  };
}

So far, I have this:

function thingsToBuy() {
  let list = [
    "milk",
    "bread",
    "bananas"
  ];
  return {
    removeItem: function(name) {
      for(let i = 0; i < list.length; i++) {
        if(list[i] === name) 
        return list.splice(i, 1)
      }
    },
    addItem: function(item) {
      list.push(item);
  
    },
    getList: function() {
      return list;
    }
  };
}

Am I missing anything or have I implemented anything wrong? Any feedback would be much appreciated!

question from:https://stackoverflow.com/questions/65895772/refactoring-methods-in-javascript-adding-deleting-items-from-an-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The solution:

function thingsToBuy() {
  var list = [
    "milk",
    "bread",
    "bananas"
  ];
  return {
    removeItem: function(name) {
      list = list.filter(item => item !== name);
      return list;
    },
    addItem: function(item) {
      list.push(item);
      return list;
    },
    getList: function() {
      return list;
    }
  };
}

This is a basic exercise to see if you understand how JS works. The function gives you some methods to mutate the list variable. You should read more about Array.filter, Array.push to see their input and output.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...