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

时间:2016-05-05 03:48:38

标签: javascript jquery

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

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 name。

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

谢谢你和问候!

3 个答案:

答案 0 :(得分:2)

将播放列表数组放入其键与ID对应的对象中。然后使用id检索正确的播放列表数组,然后按。

var playlists = {
  playlist01: [],
  playlist02: [],
  playlist01: [],
};

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

答案 1 :(得分:1)

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

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

Call函数通过传递变量作用域的当前this

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

Learn more about scope and context in JavaScript.

答案 2 :(得分:-1)

使用switch语句,因此每个可能的播放列表都有一个大小写,否则你需要使用一系列else if语句。

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

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