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 ids, you should avoid that.
This should fix it:
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);
}
A big problem with the jFiddle is you don't include jQuery. When trying to get an element by id, you cannot just reference it by name. Below is a revised version that does output what you want (though not in a nice format or anything).
$(function() {
var myData = {"timestamps":[1369008000,1369094400,1369180800,],"clicks":[1,2,3,]};
var output = $('#test');
for (var i = 0; i < myData.timestamps.length; i++) {
output.append([myData.timestamps[i], myData.clicks[i]]);
}
});
Related
I usually need to copy the output and save to a file but I have to delete/replace the second body because it'll output for however many lines I'm asking for.
myStuffData userscript.html?id=54de63cd-70fe-4251-a060-10bb80d193d8:32
Is there any way around this by outputting the text in a different manner? Here's the code I'm testing out.
function poo() {
const myStuff = document.getElementsByClassName("itg gld");
var elemCount = myStuff[0].childElementCount;
myStuff[0].children.item(0).children[0];
console.clear();
for (let i = 0; i < elemCount; i+=1) {
console.log (myStuff[0].children.item(i).children[0].href)}
}
Here's a picture of what I mean: https://i.imgur.com/6xGQofI.png
Of course. You can have a single output to pass to console.log, separating the lines with enter:
var myOutput = [];
for (let i = 0; i < 10; i++) myOutput.push(i);
console.log("\n" + myOutput.join("\n"));
I have a for-loop:
var player = 5;
for (var i = 0; i <10; i++) {
$("#id").append('<div class="game_content_text">'+json_var[i].content+'</div>');
}
The json looks like:
"content":"<script>player</script>"
Now I only want to to write down the 5 but nothing is showing...
Edit: I simplified it. Why I have to show more code? The problem is in this lines...
For example if i show a simple text from the json ("content":"example!") it works...
For explanation:
I have a buck of personal questions in the JSON Feed.
Example: "Hello 'name_variable' how are you?"
And in the the 'name_variable' i want show random names...
If we append script tag dynamically then you need to call that code which is inside newly added script.
A script tag result cannot be assign a variable or it cannot be shown as result.
You can try following example
$(function(){
var test = "this.Foo = function() {alert('hi');}";
var F=new Function (test);
(new F()).Foo(); //Shows "Hi" alert
});
I'd like to get more code simply for the fact that I can understand the context better, because your code is rather confusing.
So apparently you try to display the value player in all your appended elements?
var player = 5;
for (var i = 0, l = json_var.length; i < l; i++) {
$("#id").append('<div class="game_content_text">' + player + '</div>');
}
Otherwise, if you really need that script to be stored in the json (for some reason). I'm assuming the class "game_content_text" is only used for this.
var player = 5;
for (var i = 0, l = json_var.length; i < l; i++) {
$("#id").append('<div class="game_content_text">' + json_var[i].content + '</div>');
}
"content": "<script>$('.game_content_text').append(player);</script>"
I'm not all that familiar with jQuery, but that should work.
Also, I really do not recommend this.
I am trying to open the 5 urls inputted by the user in the textarea
But the array is not taking the url separately instead taking them altogether:
function loadUrls()
{
var myurl=new Array();
for(var i=0;i<5;i++)
{
myurl[i] = document.getElementById("urls").value.split('\n');
window.open(myurl[i]);
}
}
You only should need to split the text contents once. Then iterate over each item in that array. I think what you want is:
function loadUrls() {
var myurls = document.getElementById("urls").value.split('\n');
for(var i=0; i<myurls.length; i++) {
window.open(myurls[i]);
}
}
Here's a working example:
var input = document.getElementById('urls');
var button = document.getElementById('open');
button.addEventListener('click', function() {
var urls = input.value.split('\n');
urls.forEach(function(url){
window.open(url);
});
});
<button id="open">Open URLs</button>
<textarea id="urls"></textarea>
Note that nowadays browsers take extra steps to block popups. Look into developer console for errors.
There are a couple issues I see with this.
You are declaring a new Array and then adding values by iterating through 5 times. What happens if they put in more than 5? Or less?
split returns a list already of the split items. So if you have a String: this is a test, and split it by spaces it will return: [this, is, a, test]. There for you don't need to split the items and manually add them to a new list.
I would suggest doing something like:
var myUrls = document.getElementById("urls").value.split('\n');
for (var i = 0; i < myUrls.length; i++) {
window.open(myUrls[i]);
}
However, as others suggested, why not just use multiple inputs instead of a text area? It would be easier to work with and probably be more user friendly.
Basically:
document.getElementById("urls").value.split('\n');
returns an array with each line from textarea. To get the first line you must declare [0] after split the function because it will return the first item in Array, as split will be returning an Array with each line from textarea.
document.getElementById("urls").value.split('\n')[0];
Your function could simplify to:
function loadUrls(){
var MyURL = document.getElementById("urls").value.split('\n');//The lines
for(var i=0, Length = MyURL.length; Length > i; i++)
//Loop from 0 to length of URLs
window.open(
MyURL[i]//Open URL in array by current loop position (i)
)
}
Example:
line_1...
line_2...
... To:
["line_1","line_2"]
I have a array that has IDs in JavaScript:
["1649545","1649546","1649547"] etc.
And I want to print the values of this array in a URL, so something like this the foreach function of PHP does;
foreach
www.google.com/[valueofarray]
end
I know the solution could be very easy, but I just cannot manage to find it.
I made a fiddle and used a for loop this is without the use of jQuery but only javascript. I made an example array called myArray, I used .length so that javascript stops when he's been through all of the strings in the example array.
var myArray = ['12345', '123456', '1234567'];
for (var i = 0; i < myArray.length; i++) {
console.log('http://foo.com/' + myArray[i]);
// alert(myArray[i]);
}
See it work (and be sure to open your browsers console or use alert instead for viewing the output)
jsFiddle
var p='http:',a=["1649545","1649546","1649547"],u='www.google.com';for(i=0; i<a.length; ++i) console.log([p,'',u,a[i]].join('/'));
Try this:
var idArray = ["1649545","1649546","1649547"];
var url = "www.google.com/";
idArray.forEach(function(id){
console.log("http://" + url + id);
});
https://jsfiddle.net/tcmn2Lda/
var keys = [7925181,"68113227"];
var vals = {"7925181":["68113227"],"68113227":["7925181"]};
var temp = [];
for (var i = 0; i < keys.length; i++) {
temp[keys[i]] = vals[keys[i]];
}
//alert(JSON.stringify(vals).length);
alert(JSON.stringify(temp).length);
When I run that script in Chrome I get, after a good amount of time, an output of 340666156.
My question is... how?
The commented out alert outputs 47. Seems to me that the second alert should yield the same result? That temp should pretty much be an exact copy of val?
The jsfiddle of it:
http://jsfiddle.net/vMMd2/
Oh - and if you want to crash your browser window (well it crashed my Google Chrome window) just add the following to the end:
temp.forEach(function(entry) {
alert(temp);
});
Any ideas?
var keys = [7925181,"68113227"];
var vals = {"7925181":["68113227"],"68113227":["7925181"]};
var temp = {}; // <--- !!!
for (var i = 0; i < keys.length; i++) {
temp[keys[i]] = vals[keys[i]];
}
//alert(JSON.stringify(vals).length);
alert(JSON.stringify(temp).length);
http://jsfiddle.net/zerkms/vMMd2/2/
You're creating a sparse array, and presumably V8 initializes all the gaps with some garbage null undefined values (thanks to nnnnnn for checking that). It takes some time
#zerkms, is right. But I also wanted to pointed out why this is happening.
> var temp = [];
> temp[10] = 'test';
> temp
[ , , , , , , , , , , 'test' ]
As you can see, it creates 9 undefined values. I ran the above with nodejs so the null values are not showing up.
If I did JSON.stringfy() then you would see:
> JSON.stringify(temp)
'[null,null,null,null,null,null,null,null,null,null,"test"]'