将变量传递给方法

时间:2014-12-23 11:23:16

标签: javascript

我有以下方法,但是当我在此方法中使用变量时,它会将其检测为字符串(给出NaN错误)。这些变量是第1章,第2章,第3章,第4章和第5章。我该如何解决这个问题。

由于

    var chap1 = 0;
    var chap2 = 104;
    var chap3 = 235;
    var chap4 = 309;
    var chap5 = 406;

    ChapterMarkerPlayer.insert({
      container: 'captions-session-player',
      videoId: youtubeId + '?wmode=opaque&theme=light&autohide=0&modestbranding=1&rel=0&autoplay=0',
      width: 469,
      chapters: {
            chap1: '<span style="display: inline-block; width: 88%;">Chapter 1: Evaluating our industry’s track record on innovation</span>',
            chap2: '<span style="display: inline-block; width: 88%;">Chapter 2: Can asset managers learn from top innovators in other industries?</span>',
            chap3: '<span style="display: inline-block; width: 88%;">Chapter 3: How does multi-asset investing align with investor needs?</span>',
            chap4: '<span style="display: inline-block; width: 88%;">Chapter 4: Can investment industry innovators improve investor trust? </span>',
            chap5: '<span style="display: inline-block; width: 88%;">Chapter 5: Will regulators help to improve trust in our industry?</span>'
      }
    });

2 个答案:

答案 0 :(得分:0)

如果要在对象中使用变量作为属性名称,则应使用括号表示法。在您的情况下,它将如下所示:

var chap1 = 0;
var chap2 = 104;
var chap3 = 235;
var chap4 = 309;
var chap5 = 406;

var chapters = {};
chapters[chap1] = '<span style="display: inline-block; width: 88%;">Chapter 1: Evaluating our industry’s track record on innovation</span>';
chapters[chap2] = '<span style="display: inline-block; width: 88%;">Chapter 2: Can asset managers learn from top innovators in other industries?</span>';
chapters[chap3] = '<span style="display: inline-block; width: 88%;">Chapter 3: How does multi-asset investing align with investor needs?</span>';
chapters[chap4] = '<span style="display: inline-block; width: 88%;">Chapter 4: Can investment industry innovators improve investor trust? </span>';
chapters[chap5] = '<span style="display: inline-block; width: 88%;">Chapter 5: Will regulators help to improve trust in our industry?</span>';

ChapterMarkerPlayer.insert({
    container: 'captions-session-player',
    videoId: youtubeId + '?wmode=opaque&theme=light&autohide=0&modestbranding=1&rel=0&autoplay=0',
    width: 469,
    chapters: chapters
});

答案 1 :(得分:0)

初始化对象时,不能将变量用作键。声明后,您可以将变量用作键。喜欢

var a = 1;
var b = 2;
var c = {};
c[a] = "a";
c[b] = "b";

你不能这样做

var c = {a : "a", b: "b"}

会出错;