$.each index initial value - javascript

As we know the index of $.each will start from zero. I want to print the index from 1 to 10, as I have 10 array.
$.each(myArr, function(i){
console.log(i++);
}
why is it I'm getting from 0 still?

Try this.
$.each(myArr, function(i){
console.log(++i);
})
This is a difference between prefix and postfix operator. Prefix operator increases the value after the current operation is done. Postfix operator increases the value first and executes the current statement. This above code is for just explaining things.
As #Ghazgkull suggested, it is better to use i+1 which conveys the indent of the code.

The ++ operator AFTER the variable increases that variable after the current call is finished (in your case, after the console log call), which is why you see it starting from 0.
Since it's an index, there's no need for you to manually increase its value, but a simple console.log(i+1); would work just fine.
Otherwise, you can increase it BEFORE the current call, by putting ++ before the variable, as #Satya said in the comments.
See it here:
var myArr = [1,1,1,1,1,1,1,1,1,1];
$.each(myArr, function(i){
console.log(i+1);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

When the ++ operator is applied on the right side of the variable (i++), the current value before incrementing is used. You should use ++i if you want to get the value after incrementing.

$.each() increments the value for you. You don't need to increment it yourself. Your code should be:
$.each(myArr, function(i) {
console.log(i + 1);
}
Even if ++i works in this case, you shouldn't use an incrementor here. To any experienced programmer, it will look like you're trying to increment a value in a way that doesn't make sense. Using i + 1 makes it clear that you're simply computing a value.

Related

Javascript variable not incrementing over interval

I am trying to increment a value (in this case a UNIX timestamp, but for all we care in this case it might as well be any old integer) every 1 second, but it refuses to do so (it just stays the same).
Here's the code
// given integer starting point
var tsmin=1332449260;
setInterval(function(){
tsmin=tsmin++;
console.info(ts);
}, 1000);
The statement:
tsmin = tsmin++;
is guaranteed to keep "tsmin" at its same value forever. The ++ operator after the variable means that the value of that expression is the value before the increment. The = operator binds less tightly than ++, so the process there is:
get the value of "tsmin"
increment "tsmin"
set "tsmin" to the value from step 1.
The issue comes from the difference between ++tsmin and tsmin++.
++tsmin increments the value before doing the next step, whereas tsmin++ increments the value afterwords. If you changed the line to:
tsmin = ++tsmin
it would work, because it is now incrementing before saving it as the new value. However, even though this solution 'works', what you really should do is:
tsmin++
There is no need to set tsmin if you are just incrementing like that.
Why don't you just do tsmin++ instead of using the side affect of tsmin=tsmin++?
setInterval(function(){
tsmin+=1;
console.info(tsmin);
}, 1000);
setInterval(function(){
tsmin=++tsmin;
console.info(tsmin);
}, 1000);
Try this:
var tsmin = 1332449260;
setInterval(function() {
console.info(tsmin);
tsmin++;
}, 1000);​
This assumes you want 1332449260 to be outputted in the console as the first value, if you want to start at 1332449261 move the tsmin++; before the console.info(tsmin);.

Trying to number objects in jQuery

I'm trying to number objects, which can be added to a cart with drag'n'drop. So, this snippet should check the current number written in span.amountVal, and easily add ´+1´ to this number, but the result is always ´1´. When I uncomment the ´alert(i++);´, the snippet work like I want to. I'm confused, what is this about?
$.favList.find("div[data-asset-id="+ _itemID +"]").each(function() {
var i = $(this).find("span.amountVal").text();
// alert(i++);
$(this).find("span.amountVal").text(i++);
});
Thank you.
i++ first returns the value of i, then increments it. When you have the alert( i++ ) in place, the variable is already once incremented.
Put the ++ in front of the variable:
$(this).find("span.amountVal").text( ++i );
Or simply add one to it since you're discarding the variable right after:
$(this).find("span.amountVal").text( i + 1 );
you have a pre-increment/post-increment issue, the following change should solve it:
$.favList.find("div[data-asset-id="+ _itemID +"]").each(function() {
var i = $(this).find("span.amountVal").text();
$(this).find("span.amountVal").text(++i);
});
Pre-Increment adds one to i and then returns i while Post-Increment adds 1 to i after it has been returned.
Below is a similar post on StackOverflow touching on the topic:
post increment vs pre increment - Javascript Optimization
What are you guys doing? It SHOULDN'T read a SPAN's value, it's bad practice. Instead, it should read the items length (inside an object, for example) and then display it.

Simple Confusing Loops and Variable working

In this question,I'm asking how the following snippets work, as it involves weird use of variable:
while (+(+i--)!=0)
{
i-=i++;
}
console.log(i);
Interesting problem... you've tagged it Java, JavaScript and C -- note that while these languages have the same syntax, this question involves very subtle semantics that may (I'm not sure) differ across languages.
Let's break it down:
+(+i--)
The -- postfix decrement operator is most tightly bound. So this is equivalent to +(+(i--)). That is therefore equivalent to the value of +(+i) (that is, i), but it also decrements i after taking the value. It compares the value with 0 to see if the loop should continue. Thus, while (+(+i--)!=0) is equivalent to the following:
while (i-- != 0)
Note that it also performs i-- at the end of the loop.
Inside the loop, I believe you have some undefined behaviour, at least in C, because you are referencing i on the right, and also updating i on the left -- I believe that C doesn't define which order to do that in. So your results will probably vary from compiler to compiler. Java, at least, is consistent, so I'll give the Java answer. i-=i++ is equivalent i = i - i++, which is equivalent to to reading all the values out of the expression, computing the result of the expression, applying the post-increment, and then assigning the result back. That is:
int t = i - i; // Calculate the result of the expression "i - i++"
i++; // Post-increment i
i = t; // Store the result back
Clearly, this is the same as writing i = 0. So the body of the loop sets i to 0.
Thus, the loop executes just one time, setting i to 0. Then, it decrements i one more time on the next while loop, but fails the check because i (before decrementing) == 0.
Hence, the final answer is -1, no matter what the initial value for i is.
To put this all together and write an equivalent program:
while (i-- != 0)
{
int t = i - i;
i++;
i = t;
}
console.log(i);
When I tried it in Java and JavaScript, that's what I got. For GCC (C compiler), it gives -1 only when i starts out as 0. If i starts out as anything else, it goes into an infinite loop.
That's because in GCC (not necessarily all C compilers), i-=i++ has a different meaning: it does the store back to i first, then does the post-increment. Therefore, it is equivalent to this:
int t = i - i; // Calculate the result of the expression "i - i++"
i = t; // Store the result back
i++; // Post-increment i
That's equivalent to writing i = 1. Therefore, on the first iteration, it sets i to 1, and then on the loop, it checks whether i == 0, and it isn't, so it goes around again, always setting i to 1. This will never terminate, but for the special case where i starts out as 0; then it will always terminate the loop and decrement i (so you get -1).
Another C compiler may choose to act like Java instead. This shows that you should never write code which both assigns and postincrements the same variable: you never know what will happen!
Edit: I tried to be too clever using that for loop; that wasn't equivalent. Turned back into a while loop.
That's soooo wierd! (I love it)
first, you can forget about the +(+...) part, it's just like saying 1 + (+1) = 2.
i-- means i = i - 1. In your while condition, you test if i-- is different from 0. Note: the test is made on i != 0 and then i's value is changed. If you wanted to change its value before the test, you should have used --i instead.
As for the i -= i++, it's a very dumb way to say i = 0. You must read it from right to left: i = i + 1 and then i = i - i1 (whatever value of i you have, you'll end up with 0.
Simplier quivalent snippet:
while (i-- != 0) {
i = 0;
}
console.log(i);
1 a -= b means a = a - b.
i -= i++ would mean a similar thing to i = i-i; i++ (if you make the -= explicit).
In a similar fashion, you can pull the side effect of i-- out of the loop condition by
transforming while (foo(i--)) { ... } to while (foo(i)) { i--; ...} i--; (you need to put it both in the loop body and after the loop because, at the end, the condition will be false and the loop body will not be executed but execution continues after the while loop).
The while condition evaluation happens based on operator precedence. I have used explicit braces to help understand the evaluation:
(+(+(i--)) != 0) which is equivalent to using (i-- != 0) as the '+' are just unary operators.
The expression i -=i++; is equivalent to i = i - i++; where the LHS expression gets evaluated from left to right.
i = 4;
while (+(+i--)!=0) //here i would be decremented once to 3.
{
i-=i++; // here i = 3 - 3 = 0; even though i has been incremented by 1 its value is set to 0 with this assignment
}
This is very simple. And I think the only reason to code like this is a concept called "code obfucasion" or "code confusing". This way makes the code harder to read and debug, so that can prevent from reverse engineer your code :-)

JavaScript Infinitely Looping slideshow with delays?

How do I make an infinite loop in JavaScript? I'm trying to make a slideshow, which I have working, but I can't get it to loop. I can't even get it to loop twice.
The code I'm using right now is
window.onload = function start() {
slide();
}
function slide() {
var num = 0;
for (num=0;num<=10;num++) {
setTimeout("document.getElementById('container').style.marginLeft='-600px'",3000);
setTimeout("document.getElementById('container').style.marginLeft='-1200px'",6000);
setTimeout("document.getElementById('container').style.marginLeft='-1800px'",9000);
setTimeout("document.getElementById('container').style.marginLeft='0px'",12000);
}
}
Without the for thing in there, it does go through once. When I put in a for, it either makes Firefox lock up, or just loops once. I'm sure this is a really simple thing to do, and even if it has to be loop 1,000,000 times or something instead of infinite, that'd work fine for me.
Also, I don't want to use jQuery or something that someone else created. I'm learning JavaScript, and this is partially to help me learn, and partially because I'm trying to make as many HTML5-based systems as I can.
EDIT: I think the reason it's freezing is because it executes the code all at once, and then just stores it in a cache or something. What I want it to do is go through this once, then start at the top again, which is what I've always thought loops where for. In "batch" (command prompt) scripting, this could be done with a "GOTO" command. I don't know if there's an equivalent in JS or not, but that's really my goal.
The correct approach is to use a single timer. Using setInterval, you can achieve what you want as follows:
window.onload = function start() {
slide();
}
function slide() {
var num = 0, style = document.getElementById('container').style;
window.setInterval(function () {
// increase by num 1, reset to 0 at 4
num = (num + 1) % 4;
// -600 * 1 = -600, -600 * 2 = -1200, etc
style.marginLeft = (-600 * num) + "px";
}, 3000); // repeat forever, polling every 3 seconds
}
You don't want while(true), that will lock up your system.
What you want instead is a timeout that sets a timeout on itself, something like this:
function start() {
// your code here
setTimeout(start, 3000);
}
// boot up the first call
start();
Here's a nice, tidy solution for you: (also see the live demo ->)
window.onload = function start() {
slide();
}
function slide() {
var currMarg = 0,
contStyle = document.getElementById('container').style;
setInterval(function() {
currMarg = currMarg == 1800 ? 0 : currMarg + 600;
contStyle.marginLeft = '-' + currMarg + 'px';
}, 3000);
}
Since you are trying to learn, allow me to explain how this works.
First we declare two variables: currMarg and contStyle. currMarg is an integer that we will use to track/update what left margin the container should have. We declare it outside the actual update function (in a closure), so that it can be continuously updated/access without losing its value. contStyle is simply a convenience variable that gives us access to the containers styles without having to locate the element on each interval.
Next, we will use setInterval to establish a function which should be called every 3 seconds, until we tell it to stop (there's your infinite loop, without freezing the browser). It works exactly like setTimeout, except it happens infinitely until cancelled, instead of just happening once.
We pass an anonymous function to setInterval, which will do our work for us. The first line is:
currMarg = currMarg == 1800 ? 0 : currMarg + 600;
This is a ternary operator. It will assign currMarg the value of 0 if currMarg is equal to 1800, otherwise it will increment currMarg by 600.
With the second line, we simply assign our chosen value to containers marginLeft, and we're done!
Note: For the demo, I changed the negative values to positive, so the effect would be visible.
Perhps this is what you are looking for.
var pos = 0;
window.onload = function start() {
setTimeout(slide, 3000);
}
function slide() {
pos -= 600;
if (pos === -2400)
pos = 0;
document.getElementById('container').style.marginLeft= pos + "px";
setTimeout(slide, 3000);
}
You are calling setTimeout() ten times in a row, so they all expire almost at the same time. What you actually want is this:
window.onload = function start() {
slide(10);
}
function slide(repeats) {
if (repeats > 0) {
document.getElementById('container').style.marginLeft='-600px';
document.getElementById('container').style.marginLeft='-1200px';
document.getElementById('container').style.marginLeft='-1800px';
document.getElementById('container').style.marginLeft='0px';
window.setTimeout(
function(){
slide(repeats - 1)
},
3000
);
}
}
This will call slide(10), which will then set the 3-second timeout to call slide(9), which will set timeout to call slide(8), etc. When slide(0) is called, no more timeouts will be set up.
You can infinitely loop easily enough via recursion.
function it_keeps_going_and_going_and_going() {
it_keeps_going_and_going_and_going();
}
it_keeps_going_and_going_and_going()
The key is not to schedule all pics at once, but to schedule a next pic each time you have a pic shown.
var current = 0;
var num_slides = 10;
function slide() {
// here display the current slide, then:
current = (current + 1) % num_slides;
setTimeout(slide, 3000);
}
The alternative is to use setInterval, which sets the function to repeat regularly (as opposed to setTimeout, which schedules the next appearance only.
Expanding on Ender's answer, let's explore our options with the improvements from ES2015.
First off, the problem in the asker's code is the fact that setTimeout is asynchronous while loops are synchronous. So the logical flaw is that they wrote multiple calls to an asynchronous function from a synchronous loop, expecting them to execute synchronously.
function slide() {
var num = 0;
for (num=0;num<=10;num++) {
setTimeout("document.getElementById('container').style.marginLeft='-600px'",3000);
setTimeout("document.getElementById('container').style.marginLeft='-1200px'",6000);
setTimeout("document.getElementById('container').style.marginLeft='-1800px'",9000);
setTimeout("document.getElementById('container').style.marginLeft='0px'",12000);
}
}
What happens in reality, though, is that...
The loop "simultaneously" creates 44 async timeouts set to execute 3, 6, 9 and 12 seconds in the future. Asker expected the 44 calls to execute one-after-the-other, but instead, they all execute simultaneously.
3 seconds after the loop finishes, container's marginLeft is set to "-600px" 11 times.
3 seconds after that, marginLeft is set to "-1200px" 11 times.
3 seconds later, "-1800px", 11 times.
And so on.
You could solve this by changing it to:
function setMargin(margin){
return function(){
document.querySelector("#container").style.marginLeft = margin;
};
}
function slide() {
for (let num = 0; num <= 10; ++num) {
setTimeout(setMargin("-600px"), + (3000 * (num + 1)));
setTimeout(setMargin("-1200px"), + (6000 * (num + 1)));
setTimeout(setMargin("-1800px"), + (9000 * (num + 1)));
setTimeout(setMargin("0px"), + (12000 * (num + 1)));
}
}
But that is just a lazy solution that doesn't address the other issues with this implementation. There's a lot of hardcoding and general sloppiness here that ought to be fixed.
Lessons learnt from a decade of experience
As mentioned at the top of this answer, Ender already proposed a solution, but I would like to add on to it, to factor in good practice and modern innovations in the ECMAScript specification.
function format(str, ...args){
return str.split(/(%)/).map(part => (part == "%") ? (args.shift()) : (part)).join("");
}
function slideLoop(margin, selector){
const multiplier = -600;
let contStyle = document.querySelector(selector).style;
return function(){
margin = ++margin % 4;
contStyle.marginLeft = format("%px", margin * multiplier);
}
}
function slide() {
return setInterval(slideLoop(0, "#container"), 3000);
}
Let's go over how this works for the total beginners (note that not all of this is directly related to the question):
format
function format
It's immensely useful to have a printf-like string formatter function in any language. I don't understand why JavaScript doesn't seem to have one.
format(str, ...args)
... is a snazzy feature added in ES6 that lets you do lots of stuff. I believe it's called the spread operator. Syntax: ...identifier or ...array. In a function header, you can use it to specify variable arguments, and it will take every argument at and past the position of said variable argument, and stuff them into an array. You can also call a function with an array like so: args = [1, 2, 3]; i_take_3_args(...args), or you can take an array-like object and transform it into an array: ...document.querySelectorAll("div.someclass").forEach(...). This would not be possible without the spread operator, because querySelectorAll returns an "element list", which isn't a true array.
str.split(/(%)/)
I'm not good at explaining how regex works. JavaScript has two syntaxes for regex. There's the OO way (new RegExp("regex", "gi")) and there's the literal way (/insert regex here/gi). I have a profound hatred for regex because the terse syntax it encourages often does more harm than good (and also because they're extremely non-portable), but there are some instances where regex is helpful, like this one. Normally, if you called split with "%" or /%/, the resulting array would exclude the "%" delimiters from the array. But for the algorithm used here, we need them included. /(%)/ was the first thing I tried and it worked. Lucky guess, I suppose.
.map(...)
map is a functional idiom. You use map to apply a function to a list. Syntax: array.map(function). Function: must return a value and take 1-2 arguments. The first argument will be used to hold each value in the array, while the second will be used to hold the current index in the array. Example: [1,2,3,4,5].map(x => x * x); // returns [1,4,9,16,25]. See also: filter, find, reduce, forEach.
part => ...
This is an alternative form of function. Syntax: argument-list => return-value, e.g. (x, y) => (y * width + x), which is equivalent to function(x, y){return (y * width + x);}.
(part == "%") ? (args.shift()) : (part)
The ?: operator pair is a 3-operand operator called the ternary conditional operator. Syntax: condition ? if-true : if-false, although most people call it the "ternary" operator, since in every language it appears in, it's the only 3-operand operator, every other operator is binary (+, &&, |, =) or unary (++, ..., &, *). Fun fact: some languages (and vendor extensions of languages, like GNU C) implement a two-operand version of the ?: operator with syntax value ?: fallback, which is equivalent to value ? value : fallback, and will use fallback if value evaluates to false. They call it the Elvis Operator.
I should also mention the difference between an expression and an expression-statement, as I realize this may not be intuitive to all programmers. An expression represents a value, and can be assigned to an l-value. An expression can be stuffed inside parentheses and not be considered a syntax error. An expression can itself be an l-value, although most statements are r-values, as the only l-value expressions are those formed from an identifier or (e.g. in C) from a reference/pointer. Functions can return l-values, but don't count on it. Expressions can also be compounded from other, smaller expressions. (1, 2, 3) is an expression formed from three r-value expressions joined by two comma operators. The value of the expression is 3. expression-statements, on the other hand, are statements formed from a single expression. ++somevar is an expression, as it can be used as the r-value in the assignment expression-statement newvar = ++somevar; (the value of the expression newvar = ++somevar, for example, is the value that gets assigned to newvar). ++somevar; is also an expression-statement.
If ternary operators confuse you at all, apply what I just said to the ternary operator: expression ? expression : expression. Ternary operator can form an expression or an expression-statement, so both of these things:
smallest = (a < b) ? (a) : (b);
(valueA < valueB) ? (backup_database()) : (nuke_atlantic_ocean());
are valid uses of the operator. Please don't do the latter, though. That's what if is for. There are cases for this sort of thing in e.g. C preprocessor macros, but we're talking about JavaScript here.
args.shift()
Array.prototype.shift. It's the mirror version of pop, ostensibly inherited from shell languages where you can call shift to move onto the next argument. shift "pops" the first argument out of the array and returns it, mutating the array in the process. The inverse is unshift. Full list:
array.shift()
[1,2,3] -> [2,3], returns 1
array.unshift(new-element)
[element, ...] -> [new-element, element, ...]
array.pop()
[1,2,3] -> [1,2], returns 3
array.push(new-element)
[..., element] -> [..., element, new-element]
See also: slice, splice
.join("")
Array.prototype.join(string). This function turns an array into a string. Example: [1,2,3].join(", ") -> "1, 2, 3"
slide
return setInterval(slideLoop(0, "#container"), 3000);
First off, we return setInterval's return value so that it may be used later in a call to clearInterval. This is important, because JavaScript won't clean that up by itself. I strongly advise against using setTimeout to make a loop. That is not what setTimeout is designed for, and by doing that, you're reverting to GOTO. Read Dijkstra's 1968 paper, Go To Statement Considered Harmful, to understand why GOTO loops are bad practice.
Second off, you'll notice I did some things differently. The repeating interval is the obvious one. This will run forever until the interval is cleared, and at a delay of 3000ms. The value for the callback is the return value of another function, which I have fed the arguments 0 and "#container". This creates a closure, and you will understand how this works shortly.
slideLoop
function slideLoop(margin, selector)
We take margin (0) and selector ("#container") as arguments. The margin is the initial margin value and the selector is the CSS selector used to find the element we're modifying. Pretty straightforward.
const multiplier = -600;
let contStyle = document.querySelector(selector).style;
I've moved some of the hard coded elements up. Since the margins are in multiples of -600, we have a clearly labeled constant multiplier with that base value.
I've also created a reference to the element's style property via the CSS selector. Since style is an object, this is safe to do, as it will be treated as a reference rather than a copy (read up on Pass By Sharing to understand these semantics).
return function(){
margin = ++margin % 4;
contStyle.marginLeft = format("%px", margin * multiplier);
}
Now that we have the scope defined, we return a function that uses said scope. This is called a closure. You should read up on those, too. Understanding JavaScript's admittedly bizarre scoping rules will make the language a lot less painful in the long run.
margin = ++margin % 4;
contStyle.marginLeft = format("%px", margin * multiplier);
Here, we simply increment margin and modulus it by 4. The sequence of values this will produce is 1->2->3->0->1->..., which mimics exactly the behavior from the question without any complicated or hard-coded logic.
Afterwards, we use the format function defined earlier to painlessly set the marginLeft CSS property of the container. It's set to the currnent margin value multiplied by the multiplier, which as you recall was set to -600. -600 -> -1200 -> -1800 -> 0 -> -600 -> ...
There are some important differences between my version and Ender's, which I mentioned in a comment on their answer. I'm gonna go over the reasoning now:
Use document.querySelector(css_selector) instead of document.getElementById(id)
querySelector was added in ES6, if I'm not mistaken. querySelector (returns first found element) and querySelectorAll (returns a list of all found elements) are part of the prototype chain of all DOM elements (not just document), and take a CSS selector, so there are other ways to find an element than just by its ID. You can search by ID (#idname), class (.classname), relationships (div.container div div span, p:nth-child(even)), and attributes (div[name], a[href=https://google.com]), among other things.
Always track setInterval(fn, interval)'s return value so it can later be closed with clearInterval(interval_id)
It's not good design to leave an interval running forever. It's also not good design to write a function that calls itself via setTimeout. That is no different from a GOTO loop. The return value of setInterval should be stored and used to clear the interval when it's no longer needed. Think of it as a form of memory management.
Put the interval's callback into its own formal function for readability and maintainability
Constructs like this
setInterval(function(){
...
}, 1000);
Can get clunky pretty easily, especially if you are storing the return value of setInterval. I strongly recommend putting the function outside of the call and giving it a name so that it's clear and self-documenting. This also makes it possible to call a function that returns an anonymous function, in case you're doing stuff with closures (a special type of object that contains the local state surrounding a function).
Array.prototype.forEach is fine.
If state is kept with the callback, the callback should be returned from another function (e.g. slideLoop) to form a closure
You don't want to mush state and callbacks together the way Ender did. This is mess-prone and can become hard to maintain. The state should be in the same function that the anonymous function comes from, so as to clearly separate it from the rest of the world. A better name for slideLoop could be makeSlideLoop, just to make it extra clear.
Use proper whitespace. Logical blocks that do different things should be separated by one empty line
This:
print(some_string);
if(foo && bar)
baz();
while((some_number = some_fn()) !== SOME_SENTINEL && ++counter < limit)
;
quux();
is much easier to read than this:
print(some_string);
if(foo&&bar)baz();
while((some_number=some_fn())!==SOME_SENTINEL&&++counter<limit);
quux();
A lot of beginners do this. Including little 14-year-old me from 2009, and I didn't unlearn that bad habit until probably 2013. Stop trying to crush your code down so small.
Avoid "string" + value + "string" + .... Make a format function or use String.prototype.replace(string/regex, new_string)
Again, this is a matter of readability. This:
format("Hello %! You've visited % times today. Your score is %/% (%%).",
name, visits, score, maxScore, score/maxScore * 100, "%"
);
is much easier to read than this horrific monstrosity:
"Hello " + name + "! You've visited " + visits + "% times today. " +
"Your score is " + score + "/" + maxScore + " (" + (score/maxScore * 100) +
"%).",
edit: I'm pleased to point out that I made in error in the above snippet, which in my opinion is a great demonstration of how error-prone this method of string building is.
visits + "% times today"
^ whoops
It's a good demonstration because the entire reason I made that error, and didn't notice it for as long as I did(n't), is because the code is bloody hard to read.
Always surround the arguments of your ternary expressions with parens. It aids readability and prevents bugs.
I borrow this rule from the best practices surrounding C preprocessor macros. But I don't really need to explain this one; see for yourself:
let myValue = someValue < maxValue ? someValue * 2 : 0;
let myValue = (someValue < maxValue) ? (someValue * 2) : (0);
I don't care how well you think you understand your language's syntax, the latter will ALWAYS be easier to read than the former, and readability is the the only argument that is necessary. You read thousands of times more code than you write. Don't be a jerk to your future self long-term just so you can pat yourself on the back for being clever in the short term.
Here:
window.onload = function start() {
slide();
}
function slide() {
var num = 0;
for (num=0;num==10;) {
setTimeout("document.getElementById('container').style.marginLeft='-600px'",3000);
setTimeout("document.getElementById('container').style.marginLeft='-1200px'",6000);
setTimeout("document.getElementById('container').style.marginLeft='-1800px'",9000);
setTimeout("document.getElementById('container').style.marginLeft='0px'",12000);
}
}
That makes it keep looping alright! That's why it isn't runnable here.
try this:
window.onload = function start() {
slide();
}
function slide() {
setInterval("document.getElementById('container').style.marginLeft='-600px'",3000);
setInterval("document.getElementById('container').style.marginLeft='-1200px'",6000);
setInterval("document.getElementById('container').style.marginLeft='-1800px'",9000);
setInterval("document.getElementById('container').style.marginLeft='0px'",12000);
}
setInterval is basically an 'infinite loop' and it wont black up the browser. it waits the required time, then goes again
you can use requestAnimationFrame() function like in the below,
function unlimited () {
requestAnimationFrame(unlimited);
console.log("arian")
}
unlimited();

JavaScript Incrementing a number in an array

I want to increment a value in a array when a link is pressed in JavaScript
i Used the following code
<script type="text/javascript">
var i=0;
var numbers = new Array();
function go(val){
numbers[i]=val;
i++;
alert(numbers[i]);
}
</script>
Called the Function like this
<a href='javascript:go(1)' </a>
but always the alert prompts me 'undefined'
The alert is correct -- before you do your alert, you incremented i. You're looking at the next element after the one you just entered.
After calling the method once, your array looks like this:
numbers[0] = 1;
numbers[1] = undefined;
and i == 1.
After calling it again, the array looks like:
numbers[0] = 1;
numbers[1] = 1;
numbers[2] = undefined;
and i == 2.
Hopefully you can see that this method will always alert undefined
That's because you increment "i"
i++;
right before you put up the alert! Thus "i" will alwuays refer to the next array slot to use, not the one you just populated.
You could change the alert to use "i-1"
alert(numbers[i - 1]);
You are setting numbers[0] = 1 and then incrementing i which becomes 1 so alert(numbers[1]) is undefined, because it is undefined.
Do the alert before you increment. Also, use onclick or even better unobtrusively attach the event handlers in JS, not in the HTML.
Yes, it does that because you:
Create a completely empty array, and a pointer at 0.
When the function is called, you set the current pointer value to whatever was passed in...
...and then increment the pointer, so it's now pointing past the end of all the elements.
Now you look at the element in the array that's being pointed at, which has to be undefined because of the way you're managing the i pointer.
What were you hoping for this to do, by the way?
The question doesn't even match the code... or the code doesn't match the question?
"I want to increment a value in a array"
Your code is not incrementing the value, it's incrementing the index!
function go(val){
numbers[i]=val;
i++;
}
(where i is the index of the next undefined array element) is just the same as
numbers.push(val);
and if you need i to equal what will be the index of the next undefined array element then
i = numbers.length;
To increment the value you would have to first have numeric values for some array elements; then your function would need the index of which value to increment
var numbers = [0,0,0,0];
function go(i){
numbers[i]++;
}
// testing
go(1);
go(3);
go(1);
alert(numbers);
will show 0,2,0,1
But if your entire goal is to put a value into a new element on the end of an array then just use .push()
and .length will tell you how many elements there are; there is no need to increment an i

Categories

Resources