Friday, 15 March 2013

javascript - Pass JSON data value key to function -


I am drawing a line on the canvas using the data provided by a JSON object:

  var data = {value: [{X: "04-28", Xt: "7:45 PM", YS: 116, WD: 74, YP: 0}, {X: "04-29", XT: "2: 00 am", Ys: 112, Yd: 73, Yp: 0}, //   

Using a bit of jQuery to draw a line:

  C.lineWidth = 4; C.strokeStyle = '# f00'; C.beginPath (); C.moveTo (getXPixel (0), getYPixel (data.values ​​[0] .YS); (Var i = 1; i & lt; data. Values.length; i ++) {c.lineTo (getXPixel (i), getYPixel (data.values ​​[i] .YS); } C. Stroke ();   

To take care of several lines ('yadhi' and 'yip' and to attract any other line needed later) I take that bit into the function I want to use, I can call:

  drill (4, '#faf', 'ys');   

The function I tried:

  function drawline (width, style, d) {c.lineWidth = width; C. Stroke style = style; C.beginPath (); C.moveTo (getXPixel (0), getYPixel (data.values ​​[0]. D)); {C.lineTo (getXPixel (i), getYPixel (data.values ​​[i]. D) for (var i = 1; i & lt; data.values.length; i ++); } C. Stroke (); }   

does not work, there is no error, but no line has been created. It works if I put 'YS' in the function directly. How can I pass that bit as logic?

You d property value [i] , You want the value of the string value that holds d you obj [d] , not obj.d similar to:

  function drawline (width, style, d) {c .lineWidth = width; C. Stroke style = style; C.beginPath (); C.moveTo (getXPixel (0), getYPixel (data.values ​​[0] [d])); {C.lineTo (getXPixel (i), getYPixel (data.values ​​[i] [de]) for (var i = 1; i & lt; data.values.length; i ++); } C. Stroke (); }   

For example:

  var obj = {a: 1, b: 2, c: 3}; Console.log (obj.a); // 1 console.log (obj ['a']); // 1 var a = 'b'; Console.log (obj.a); // 1, still console.log (obj [a]); // 2, because var is a == 'B' as: console.log (obj ['b']); // 2    

No comments:

Post a Comment