You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据videos数组长度向createVideo函数动态传递视频链接参数

解决方案

直接用JavaScript的**扩展运算符(...)**就能实现动态传递数组所有元素作为函数参数,修改load_videos函数即可:

function add_vid() {
  // 建议添加let/const声明避免全局变量污染
  const url_input = document.getElementById("vid_url");
  const url = url_input.value;
  videos.push(url);
  url_input.value = "";
  load_videos();
}

function load_videos() {
    // 使用扩展运算符展开videos数组的所有元素作为参数
    p_video = createVideo(...videos);
    start = true;
}

原理说明

扩展运算符...会把数组的每一个元素拆解成独立的参数传递给函数:

  • 当videos = ['vid1', 'vid2']时,createVideo(...videos)等价于createVideo(videos[0], videos[1])
  • 当数组长度增加时,会自动匹配参数数量,无需手动修改代码

如果需要兼容不支持ES6的老旧浏览器,可以用Function.prototype.apply()方法替代:

p_video = createVideo.apply(null, videos);

apply方法的第二个参数为数组,它会自动将数组元素拆解为独立参数传递给目标函数,效果和扩展运算符完全一致。

内容的提问来源于stack exchange,提问作者Rohith M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 11:10:14