如何知道函数的参数中传递的var名称

How to know the var name passed in parameter for a function?

本文关键字:var 名称 参数 何知道 函数      更新时间:2023-09-26

这就是我所拥有的(示例):

HTML:

<button id="playlist01"></button>
<button id="playlist02"></button>
<button id="playlist03"></button>

jQuery:

$(function() {
  var playlist01 = [];
  var playlist02 = [];
  var playlist03 = [];
  $("button").click(function() {
    pushSong( $(this).attr("id") );
  });
  function pushSong(id) {
    playlist??.push("whatever"); //playlist01, playlist02 or playlist03 ??
  }
});

每个按钮都有一个数组,id为var名称。

当我点击一个<button>标签时,我会以按钮的id作为参数调用函数,然后,我用函数中传递的id在数组中推送一些东西,但是,我怎么能知道playlist?的名称呢?

谢谢你和问候!

将播放列表数组放在一个对象中,该对象的键与ID相对应。然后使用id检索正确的播放列表数组,然后推送。

var playlists = {
  playlist01: [],
  playlist02: [],
  playlist01: [],
};
function pushSong(id) {
  playlists[id].push("whatever");
}

所有变量的作用域都是最接近的闭包。所有函数都是闭包。您的变量位于外部函数的范围和上下文中,因此,如果您将外部函数的上下文传递给pushSong函数,则可以执行以下操作:

function pushSong(id) {
    this[id].push("whatever");
};

通过传递变量作用域所在的当前this来调用函数:

pushSong.call(this, $(this).attr("id"));

了解有关JavaScript中作用域和上下文的更多信息。

使用switch语句,这样每个可能的播放列表都有一个case,否则需要使用一系列else-if语句。

http://www.w3schools.com/js/js_switch.asp

或者将其更改为使用双数组播放列表[][]和[1][]作为第一个播放列表[2][]作为第二个播放列表等。