Still learning... again sorry if this sounds stupid:
I have 2 variables "timestamps" and "clicks" and a string of numbers:
var myData = {
"timestamps":[
1362096000000,1362355200000,1362441600000,1362528000000
],
"clicks":[
[
1,2,3,4
]
};
I'm trying to restructure that into an array in this format:
[1362096000000,1],
[1362355200000,2],
[1362441600000,3],
[1362528000000,4],
Here is what I have so far: http://jsfiddle.net/3UsP6/1/
Javascript:
var myData = {"timestamps":[1369008000,1369094400,1369180800,],"clicks":[1,2,3,]};
var output = test;
for (var i = 0, l = myData.timestamps.length; i < l; i++)
{
output.push([myData.timestamps[i], myData.clicks[i]]);
}
HTML:
<body onload="javascript:alterText()">
<a id="test"></a>
</body>
I need to output the variable into the body of the page but I can't get it to display. What am I doing wrong?
Before anything else, if you are debugging, you are better off using the debugger of the browser (F12 in most browsers). Use console.log()
to output to the console to see values. Breakpoints would be better since they pause code, and you can inspect values at that moment.
Now, for the mistakes you made:
Your output
is test
which is an <a>
. You can't do a push
since that's not an array. What you can do is create an array, fill it with values, and do a JSON.stringify
to turn it into a string.
You should use document.get*
functions, like document.getElementId()
to refer to DOM elements. Though browsers do expose globals for elements with id
s, you should avoid that.
function alterText() {
var myData = {
"timestamps": [1369008000, 1369094400, 1369180800],
"clicks": [1, 2, 3]
};
var output = [];
var link = document.getElementById('test');
for (var i = 0, l = myData.timestamps.length; i < l; i++) {
output.push([myData.timestamps[i], myData.clicks[i]]);
}
// Output to console
console.log(output);
// Convert array to text and output to element
link.innerHTML = JSON.stringify(output);
}