onClick 将项目添加到数组,限制为 3 个项目且无重复
onClick add item to array with limit to 3 items with no duplication
单击按钮时会将内容添加到数组。
- 限制为最近 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.
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);
});
单击按钮时会将内容添加到数组。
- 限制为最近 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.
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);
});