on单击"将项目添加到阵列",最多3个项目,不重复



On单击按钮将向数组中添加内容。

  • 限制最近3次点击
  • 将新内容放在数组的末尾,然后删除最旧的内容(最旧的项目将从数组中删除(
  • 所有项目向左跳一步

示例:

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.

JSFIDDLEhttps://jsfiddle.net/btcr1yL9/1/

希望这能有所帮助。

更新

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);
});

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

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链接。

最新更新