onClick 将项目添加到数组,限制为 3 个项目且无重复

onClick add item to array with limit to 3 items with no duplication

单击按钮时会将内容添加到数组。

示例:

1. If I click on button "Apple", then "Banana" then "Strawberry".
Output will be: ["Apple" , "Banana" , "Strawberry"]
** CORRECT , content jumps to left and drop last one. **

2. If I then click "Apple" it will drop the first item "Banana" and ADD "Apple" to last.
Output will be: ["Banana" , "Strawberry", "Apple"]
** CORRECT , content jumps to left and drop last one. **

3. If I then click "Banana" it will drop the first  item and ADD "Apple" to last.
Output will be: ["Apple", "Strawberry", "Banana"]
** FAIL , content does not jumps to left correct. **

Output should be: ["Strawberry", "Apple", "Banana"]
// "Strawberry" should take place 1 and "Apple" place 2.

JSFIDDLE https://jsfiddle.net/btcr1yL9/1/

这应该可以解决您的问题,

var list = [];

$('button').click(function() {

  var fruit = $(this).text();
  
  var index = list.findIndex(item => item  === fruit);
  if(index === -1) {
     list.push(fruit);
  } else {
     list.splice(index, 1);
     list.push(fruit);
  }
  if(list.length > 2) {
     list.shift();
  }
  
  console.log(list);

});

Fiddle link here.

希望这对您有所帮助。

更新

var list = [];

$('button').click(function () {
  var fruit = $(this).text();

  var index = list.indexOf(fruit);
  if (index === -1) {
    if (list.length > 2) {
      list.splice(0, 1);
    }
    list.push(fruit);
  } else {
    list.splice(index, 1);
    list.push(fruit);
  }

  console.log(list);
});