簡體   English   中英

Kinetic.js / Javascript:在不使用eval()的情況下將變量作為屬性調用?

[英]Kinetic.js / Javascript: calling a variable as a property without using eval()?

我正在嘗試自學HTML5和JavaScript,希望能對您有所幫助。 我通過使用eval()解決了一個問題,並且想知道是否還有另一種不使用eval()的方法來解決它。 我嘗試過的所有方法似乎都無效。

我有兩個數組,定義如下:

var europe = {  
    shapes: {
    AL: "M520.651,114.27l-0.257,0.900l0.385,1.160l1.029,0.643l0,0.644l-0.901,0.386l-0.128,0.901l-1.288,1.287l-0.386-0.128l-0.127-0.644l-1.417-0.900l-0.259-1.288l0.259-1.803l0.256-0.901l-0.384-0.386l-0.258-0.901l1.287-1.288l0.129,0.516l0.771-0.258l0.516,0.773l0.643,0.257l-0.130-1.030z",
    AM: "M582.697,116.33l3.605,-0.515l0.642,0.772l1.032,0.386l-0.516,0.773l1.416,0.900l-0.772,0.902l1.159,0.643l1.158,0.516l0.129,1.801l-1.029,0.129l-1.032,-1.544l0,-0.515l-1.287,0.129l-0.771,-0.772l-0.516,0l-1.029,-0.773l-2.059,-0.643l0.256,-1.288l0.386,0.901z",
    AT: "M510.996,97.278l-0.257,1.158l-1.545,0l0.643,0.643l-0.900,1.674l-0.515,0.515l-2.446,0l-1.289,0.644l-2.315-0.258l-3.734-0.644l-0.644-0.900l-2.703,0.386l-0.258,0.514l-1.672-0.386l-1.416,0l-1.160-0.514l0.385-0.644l-0.128-0.515l0.903-0.128l1.285,0.772l0.387-0.772l2.446,0.128l1.931-0.515l1.287,0.128l0.773,0.515l0.258-0.386l-0.387-1.802l1.030-0.386l0.901-1.158l2.058,0.772l1.417-1.030l1.030-0.258l2.061,0.901l1.286-0.129l1.158,0.516l-0.127,0.256l-0.257-0.903z",
    },
    names: {
    AL: "Albania",
    AM: "Armenia",
    AT: "Austria",
    }
};

我正在做的是遍歷Europe.shapes中的路徑數據以繪制它,然后使用以下代碼在Europe.names中顯示匹配的數據:

for(var euroKey in europe.shapes) {
    var pathEuro = new Kinetic.Path({
      data: europe.shapes[euroKey],
      name: euroKey,
      fill: 'yellow',
      stroke: '#555',
      strokeWidth: 1
    });

    pathEuro.on('mouseover', function() {
      var euroText = eval('europe.names.'+this.getName());
      writeMessage(euroText);
      this.setFill('#CCCCCC');
      this.moveTo(topLayer);
      topLayer.drawScene();
    }); 

    pathEuro.on('mouseout', function() {
      writeMessage('');
      this.setFill('#eee');
      this.moveTo(mapLayer);
      topLayer.draw();
    });

    textLayer.add(countryText);
    mapLayer.add(pathEuro);
};

這大部分是從此處的教程中竊取的: http : //www.html5canvastutorials.com/labs/html5-canvas-world-map-svg-path-with-kineticjs/,但我嘗試添加該國的鼠標懸停文本名稱。 這種使用eval()的方法有效,但是當我自己執行此操作時,我不想學習不良習慣。

如果有人真的很無聊並且想看看,那么整個代碼都可以在GitHub上找到: https//github.com/malkie-labs/html5-world-map 任何建設性的批評或建議,表示贊賞!

謝謝! 斯科特

如果僅使用eval訪問變量名對象成員,則可以不使用eval來執行此操作:

eval('europe.names.'+this.getName());

變成

europe.names[this.getName()];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM