Как прокрутить массив кнопкой в + и в - в JS
Сделал вот такой велосипед! при прокрутке в положительную сторон проблем нет. прокрутке в обратную сторону появляются неопределенные элементы как этого избежать ? или что я сделал не правильно.
<style>
body {
background-color: aqua;
}
#box {
width: 50px;
height: 50px;
border: 2px solid #f108f1;
background-color: black;
}
</style>
<body>
<div id="box"></div>
<button onclick="as.back()"></button>
<button onclick="as.go()"></button>
<script>
let as = {
color: ['red', '#f108f1', 'green'],
index: 0,
st: function (aa) {
let box = document.getElementById('box')
box.style.backgroundColor = aa;
},
go: function () {
if (this.index == this.color.length - 1) {
this.index = 0
} else {
this.index++
}
this.st(this.color[this.index])
},
// здесть при нажатии берется 2 неопредиленных елемна масива
back: function () {
if (this.index < 0) {
this.index = this.color.length
} else {
this.index--
}
this.st(this.color[this.index])
console.log(this.color[this.index])
}
}
</script>
</body>
Ответы (2 шт):
Автор решения: Laukhin Andrey
→ Ссылка
Ваш код рабочий, за исключением ошибки в методе back().
Последний элемент имеет индекс на единицу меньше, чем размер массива, поэтому правильное выражение: this.index = this.color.length - 1.
Код можно немного упростить:
var as = {
color: ['red', '#f108f1', 'green'],
index: 0,
set: function() {
let box = document.getElementById('box');
box.style.backgroundColor = this.color[this.index];
},
go: function() {
this.index = ++this.index == this.color.length ? 0 : this.index;
this.set();
},
back: function() {
this.index = --this.index < 0 ? this.color.length - 1 : this.index;
this.set();
}
}
body {
background-color: aqua;
}
#box {
width: 50px;
height: 50px;
border: 2px solid #f108f1;
background-color: black;
}
<div id="box"></div>
<button onclick="as.back()">-</button>
<button onclick="as.go()">+</button>
Автор решения: UserTest013
→ Ссылка
let as = {
color: ['red', '#f108f1', 'green'],
index: 0,
set: function() {
box.style.backgroundColor = this.color[this.index];
},
go: function() {
this.index = (this.index + 1) % this.color.length;
this.set();
},
back: function() {
this.index = (this.index - 1 + this.color.length) % this.color.length;
this.set();
}
}
#box {
width: 50px;
height: 50px;
border: 2px solid #f108f1;
background-color: black;
}
<body>
<div id="box"></div>
<button onclick="as.back()"><</button>
<button onclick="as.go()">></button>
</body>