限制数组(Javascript)
我有一个问题,设置一个限制到我自己的灯箱画廊限制数组(Javascript),javascript,arrays,limit,Javascript,Arrays,Limit,我有一个问题,设置一个限制到我自己的灯箱画廊 <script> var imagenumber = 0; function btnleft(){ load = imagenumber-=1; document.getElementById('lightboxcontent').innerHTML=imagelist[load]; } function btnright(){ load = imagenu
<script>
var imagenumber = 0;
function btnleft(){
load = imagenumber-=1;
document.getElementById('lightboxcontent').innerHTML=imagelist[load];
}
function btnright(){
load = imagenumber+=1;
if (load==undefined){load=imagenumber-=1}
document.getElementById('lightboxcontent').innerHTML=imagelist[load];
}
</script>
当我在“下一步”按钮上单击3次以上时,我收到错误消息“undefined”。
我应该怎么做才能限制我的阵列?试试看
function btnleft(){
var load = imagelist[imagenumber-=1];
if (load) // imagenumber in array boundaries
document.getElementById('lightboxcontent').innerHTML = load;
else
imagenumber = 0;
}
function btnright(){
var load = imagelist[imagenumber+=1];
if (load) // imagenumber in array boundaries
document.getElementById('lightboxcontent').innerHTML = load;
else
imagenumber = imagelist.length-1;
}
然而,Javascript中的Array
s没有大小限制,它们更像(无限)列表。您很难对它们的长度设置限制,尤其是不能使用,因为它的number参数仅用于初始化目的
您可以使用数组的属性来检查索引是否在数组边界中:
i>=0&&i
。我的代码只是检查该索引中是否有项(第二个函数似乎也打算这样做),否则会重置索引。我假设单击“下一步按钮”调用btnright()
函数
如果是这种情况,那么您正在测试未定义的的错误值。您可以将函数重写为:
function btnright(){
load = imagenumber += 1;
// Test the value at the index of the array, not your index variable.
if (imagelist[load] === undefined) {
load = imagenumber-= 1;
}
document.getElementById('lightboxcontent').innerHTML = imagelist[load];
}
从风格上来说,这仍然不是最好的。您的load
变量不是必需的,因为它的值总是重复imagenumber
。您可以重构函数,如下所示:
function btnright() {
// If we have a new array value do something.
if (imagelist[imagenumber + 1] !== undefined) {
// Increment the index and load the new image.
document.getElementById('lightboxcontent').innerHTML = imagelist[++imagenumber];
}
}
function btnleft() {
// If we're not on the first image do something.
if (imagenumber !== 0) {
// Decrement the index and load the new image.
document.getElementById('lightboxcontent').innerHTML = imagelist[--imagenumber];
}
}
您是指数组.length
值吗?
function btnright() {
// If we have a new array value do something.
if (imagelist[imagenumber + 1] !== undefined) {
// Increment the index and load the new image.
document.getElementById('lightboxcontent').innerHTML = imagelist[++imagenumber];
}
}
function btnleft() {
// If we're not on the first image do something.
if (imagenumber !== 0) {
// Decrement the index and load the new image.
document.getElementById('lightboxcontent').innerHTML = imagelist[--imagenumber];
}
}