仅调用一次后如何从数组中删除元素?
How to remove an element from an array after it's called only once?
当从videos
数组中调用一个随机元素时,应该在索引不为空且之后未定义的情况下删除它。问题是 splice_video();
一直调用同一个元素两次,而它应该在只调用一次后从数组中删除该元素。 (数组中的每个元素都是一个函数)。
function playNextVideo() {
const videos = [showVideo1,showVideo2,showVideo3,showVideo4,showVideo5];
const random_video = Math.floor(Math.random() * videos.length);
const video = videos.splice(random_video, 1);
const splice_video = video[0]();
splice_video();
}
在外部而不是内部声明函数数组,以便从数组中删除函数是持久的。
const videoFns = [showVideo1, showVideo2, showVideo3, showVideo4, showVideo5];
function playNextVideo() {
const randomIndex = Math.floor(Math.random() * videoFns.length);
const [videoFn] = videoFns.splice(randomIndex, 1);
videoFn();
}
现场演示:
const videoFns = Array.from(
{ length: 5 },
(_, i) => () => console.log('video ' + i)
);
function playNextVideo() {
if (!videoFns.length) return;
const randomIndex = Math.floor(Math.random() * videoFns.length);
const [videoFn] = videoFns.splice(randomIndex, 1);
videoFn();
}
document.querySelector('button').addEventListener('click', playNextVideo);
<button>click</button>
当从videos
数组中调用一个随机元素时,应该在索引不为空且之后未定义的情况下删除它。问题是 splice_video();
一直调用同一个元素两次,而它应该在只调用一次后从数组中删除该元素。 (数组中的每个元素都是一个函数)。
function playNextVideo() {
const videos = [showVideo1,showVideo2,showVideo3,showVideo4,showVideo5];
const random_video = Math.floor(Math.random() * videos.length);
const video = videos.splice(random_video, 1);
const splice_video = video[0]();
splice_video();
}
在外部而不是内部声明函数数组,以便从数组中删除函数是持久的。
const videoFns = [showVideo1, showVideo2, showVideo3, showVideo4, showVideo5];
function playNextVideo() {
const randomIndex = Math.floor(Math.random() * videoFns.length);
const [videoFn] = videoFns.splice(randomIndex, 1);
videoFn();
}
现场演示:
const videoFns = Array.from(
{ length: 5 },
(_, i) => () => console.log('video ' + i)
);
function playNextVideo() {
if (!videoFns.length) return;
const randomIndex = Math.floor(Math.random() * videoFns.length);
const [videoFn] = videoFns.splice(randomIndex, 1);
videoFn();
}
document.querySelector('button').addEventListener('click', playNextVideo);
<button>click</button>