How to write a loop with JavaScript - javascript

I try to make code like this:
var code1 = a, code2 = b, code3 = c;
var x = 3;
for (y = 1; y <= x; y++) {
//this part where i dont know about
alert ();
}
So how to make it alert code1, code2, and code3? I mean this alerts the values a, b, and c.
I tried with alert("code"+y); and alert(code+y); but it wont do.

So how to make it alert code1, code2, and code3? i mean this alert the value a, b, and c?
The best way is to use an array instead of discrete code1, code2, and code3 variables:
// (I assume a, b, and c have already been declared somewhere, or that your real
// code has literals?)
var codes = [a, b, c];
var y;
for (y = 0; y < codes.length; y++) {
alert(codes[y]);
}
(Note that I started y in a different place.)
While it's possible to do the code1, code2, code3 thing with global variables, global variables should be avoided whenever possible, and it's nearly always possible. (It's also possible with local variables, but you have to use eval or its cousin the Function constructor, and avoiding eval is also something you should avoid whenever possible, and is nearly always possible. :-) )
Alternately, if you find yourself wanting to do this where an array doesn't quite make sense, you can use an object instead:
var codes = {
code1: a,
code2: b,
code3: c
};
var y;
for (y = 1; y <= 3; ++y) {
alert(codes["code" + y]);
}
That works because in JavaScript, you can access an object property using either dot notation and a literal (obj.foo), or brackets notation and a string (obj["foo"]), and in the latter case the string can be the result of any expression. Since "code" + y is code1 when y is 1, codes["code" + y] looks up the property "code1" on codes (when y is 1).

Use Bracket notation
alert(window["code"+y]);
I would rather recommend you to use an array like
var code = [1, 2, 3];
for (y = 0; y < code.length; y++) {
alert(code[y]);
}

Related

Getting comma in the joined array with string

I don't know why I have a comma when I use join method. Can anyone explain?
function maskify(cc) {
var a = cc.slice(cc.length - 4, cc.length);
var b = cc.slice(0, cc.length - 4);
b = b.split("");
for (var i = 0; i < b.length; i++) {
b[i] = "#";
}
b.join("#");
console.log(b + a);
}
maskify("sadasdasdasdasdasd");
// result : #,#,#,#,#,dasd
Join() is the method of array which allows to join its element as string and returns. Join() takes one argument which is separator, the default value is ",". You need to specify empty string if you want to join without any separator. For reference refer MDN.
For your code, you are joining but not storing, and again converting it to string by using + operator with variable a
function maskify(cc) {
var a = cc.slice(cc.length - 4, cc.length);
var b = cc.slice(0, cc.length - 4);
b = b.split("");
for (var i = 0; i < b.length; i++) {
b[i] = "#";
}
var output=b.join("#");
console.log(output + a);
}
maskify("sadasdasdasdasdasd");
// result : #,#,#,#,#,dasd
When you use split on b, b is an array of individual characters. When logging b + a, since b is an array and a a string, + will act as string concatenation operator. b is converted to string using toString() implicitly. toString on array returns string of array elements joined by ,. So, you're getting comma in the final output.
Simple solution to solve this problem is to explicitly join the array elements before concatenating.
function maskify(cc) {
var a = cc.slice(cc.length - 4, cc.length);
var b = cc.slice(0, cc.length - 4);
b = b.split("");
for (var i = 0; i < b.length; i++) {
b[i] = "#";
}
b.join("#");
console.log(b.join('') + a);
}
maskify("sadasdasdasdasdasd");
Another way to achieve same results is using repeat
var str = 'sadasdasdasdasdasd';
var maskedStr = '#'.repeat(str.length -4) + str.slice(-4);
console.log(maskedStr);
Note that this is supported in latest browsers/environments only. Check the browser compatibility, if not supported use polyfill.
It's because when concatinating an array and a string, the array is implicitly converted into a string.
var array = [...];
array + "";
is the same as:
array.toString() + "";
and [4, 5].toString() is "4,5" (add a , by default).
Why?
Because, when this line is reached:
console.log(b + a);
a will be a string because it was cut from the string cc. And b is an array because it is the result of the split, and b.join don't change b to a string, it just return a string that you don't use and leaves b intact (so b remains an array).
Fix:
Use the result of b.join not b:
console.log(b.join("#") + a);
or:
b = b.join("#");
console.log(b + a);
i add
var c = b.concat(a);
c.join("");
It's working . Thanks u so much :D

how can I chop letters of a string into smaller chunks of fixed lengths in JavaScript?

Thanks in advance for taking the time to read. I am a total beginner and I know this might sound one of those "help me understand this" questions but I'm sorry if that was the case and I'll try to be specific as much as I can.
Basically I need to create a function to chop strings into smaller strings of input length, I have tried array methods but for some reason I keep getting an empty array. So that the if the input string is "hell" and the input length is 2 the output would be ["he","ll]
Also, in relevance to this problem, I was wondering if you can set a for loop condition x.length<=0.
Here is my code:
function chop(a, b) {
// a = "hell"
// b = 2
var ans = [];
var x = a.split(""); // [h,e,l,l]
for (var i = 0; i<=(x.length/b); i++) {
// condition i<=2
// I was also wondering how can set the condition to be x.length <= 0
x = x.slice(0,(b-1)); // x = "he"
ans.push(x); // ans = ["he", ]
x = x.splice(0,b); // x = [l,l]
}
console.log(ans);
}
You can do it like this:
function chop(a, b) {
var ans = [];
for (var i = 0; i < a.length; i += b) {
ans.push(a.substring(i, i + b));
}
console.log(ans);
}
chop("hello", 2); //logs ["he", "ll", "o"]
It's simple if you use regular expressions:
"hello".match(/.{1,2}/g) || []; // ["he", "ll", "o"]
However, if you don't know the value of the second parameter beforehand, it's a bit more dirty:
function chop(a, b) {
return a.match(new RegExp('.{1,'+b+'}','g')) || [];
}
chop("hello", 2); // ["he", "ll", "o"]
In that case, it would be a good idea to sanitize b before inserting it in the regex.

How to dynamically create variable name?

I need to create javascript objects that base on user defined number. So if user defines 20, then I need to create 20 variables.
var interval_1=0, interval_2=0, interval_3=0, interval_4=0, interval_5=0... interval_20=0;
how do I do it so the name of the object can be dynamically created?
for (i=0; i<=interval; i++){
var interval_ + i.toString() = i;
}
Erm, use an array?
for( i=0; i<=count; i++) array[i] = i;
Use an array:
var i, count, interval = [];
// user defines count, 20 for example
count = 20;
for (i = 0; i < count; i++) {
interval.push(i);
}
// interval[0] === 0
// interval[19] === 19
// interval.length === 20
Note, this starts the index at 0 and goes up to count - 1. Do not use i <= count unless you start i at 1.
Here is a jsFiddle to illustrate. Hit F12 to open dev tools in most browsers and look at console, or change console.log() to alert().
Link: http://jsfiddle.net/willslab/CapBN/1/
Alternatively, you could setup a single object with properties for each value:
var i, count, intervals = {};
count = 20;
for (i = 0; i < count; i++) {
intervals["interval_" + i] = i;
}
//intervals.interval_0 === 0
//intervals.interval_19 === 19)
Link: http://jsfiddle.net/willslab/EBjx7/2/
for (i=0; i<=20; i++){
window["interval_" + i.toString()] = i;
}
Javascript variables can be created by:
a variable declaration, e.g. var x;
assigning a value to an undeclared variable, e.g. y = 'foo';
an identifier in a formal parameter list, e.g. function bar(x, y, z);
using eval, e.g. eval( 'var x = 4');
If all else fails and you want say 5 variables, you can do:
var s = [];
var i = 5;
while (i--) {
s[i] = 'a' + i;
}
eval('var ' + s.join(',') + ';');
alert(a0); // shows undefined
If a0 wasn't defined, the last step would throw a reference error.
Of course the issue you now have is how to access them. If they are created as global variables, you can use:
globalObj['a' + i];
where globalObj is usually window, however there is no equivalent for accessing function variables since you can't access their variable object.
So the usual solution is to put things into arrays or objects where you can iterate over the properties to find things you don't know the name of.

Javascript How to define multiple variables on a single line?

Reading documentation online, I'm getting confused how to properly define multiple JavaScript variables on a single line.
If I want to condense the following code, what's the proper JavaScript "strict" way to define multiple javascript variables on a single line?
var a = 0;
var b = 0;
Is it:
var a = b = 0;
or
var a = var b = 0;
etc...
Using Javascript's es6 or node, you can do the following:
var [a,b,c,d] = [0,1,2,3]
And if you want to easily print multiple variables in a single line, just do this:
console.log(a, b, c, d)
0 1 2 3
This is similar to #alex gray 's answer here, but this example is in Javascript instead of CoffeeScript.
Note that this uses Javascript's array destructuring assignment
You want to rely on commas because if you rely on the multiple assignment construct, you'll shoot yourself in the foot at one point or another.
An example would be:
>>> var a = b = c = [];
>>> c.push(1)
[1]
>>> a
[1]
They all refer to the same object in memory, they are not "unique" since anytime you make a reference to an object ( array, object literal, function ) it's passed by reference and not value. So if you change just one of those variables, and wanted them to act individually you will not get what you want because they are not individual objects.
There is also a downside in multiple assignment, in that the secondary variables become globals, and you don't want to leak into the global namespace.
(function() { var a = global = 5 })();
alert(window.global) // 5
It's best to just use commas and preferably with lots of whitespace so it's readable:
var a = 5
, b = 2
, c = 3
, d = {}
, e = [];
There is no way to do it in one line with assignment as value.
var a = b = 0;
makes b global. A correct way (without leaking variables) is the slightly longer:
var a = 0, b = a;
which is useful in the case:
var a = <someLargeExpressionHere>, b = a, c = a, d = a;
Why not doing it in two lines?
var a, b, c, d; // All in the same scope
a = b = c = d = 1; // Set value to all.
The reason why, is to preserve the local scope on variable declarations, as this:
var a = b = c = d = 1;
will lead to the implicit declarations of b, c and d on the window scope.
Here is the new ES6 method of declaration multiple variables in one line:
const person = { name: 'Prince', age: 22, id: 1 };
let {name, age, id} = person;
console.log(name);
console.log(age);
console.log(id);
* Your variable name and object index need be same
Specifically to what the OP has asked, if you want to initialize N variables with the same value (e.g. 0), you can use array destructuring and Array.fill to assign to the variables an array of N 0s:
let [a, b, c, d] = Array(4).fill(0);
console.log(a, b, c, d);
note you can only do this with Numbers and Strings
you could do...
var a, b, c; a = b = c = 0; //but why?
c++;
// c = 1, b = 0, a = 0;
do this if they have same value
let x = y = z = 0
otherwise
let [x, y, z] = [10, 30, 50]
console.log(x, y, z) // 10 30 50
The compressed type of that is here:
var a, b = a = "Hi";
& for 3 variables:
var x, y, z = x = y = "Hello";
Hope to be helpful!
This is completely correct:
var str1 = str2 = str3 = "value";
And if change one of their value, the value of other variables won't change:
var str1 = str2 = str3 = "value";
/* Changing value of str2 */
str2 = "Hi Web!";
document.write("str1 = " + str1 + " - str2 = " + str2 + " - str3 = " + str3);

Regarding JavaScript for() loop voodoo

I was for quite some time under the impression that a for loop could exist solely in the following format:
for (INITIALIZER; STOP CONDITION; INC(DEC)REMENTER)
{
CODE
}
This is, however, most definitely not the case; take a look at this JavaScript implementation of the Fisher-Yates Shuffle:
shuffle = function(o)
{
for (var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
This little snippet completely blows my mind; how in the world is so much going on inside a simple for loop declaration? I mean... it doesn't even open a brace! All of the magic is being done right there inside the for statement. It'd be absolutely wonderful if somebody could provide a relatively thorough explanation as to how in the world this voodoo is doing what it does. Much appreciated in advance.
shuffle = function(o){
for (
var j, // declare j
x, // declare x
i = o.length; // declare i and set to o.length
i; // loop while i evaluates true
j = parseInt(Math.random() * i), // j=random number up to i
x = o[--i], // decrement i, and look up this index of o
o[i] = o[j], // copy the jth value into the ith position
o[j] = x // complete the swap by putting the old o[i] into jth position
);
return o;
};
This is starting with i equal to the number of positions, and each time swapping the cards i and j, where j is some random number up to i each time, as per the algorithm.
It could be more simply written without the confusing comma-set, true.
By the way, this is not the only kind of for loop in javascript. There is also:
for(var key in arr) {
value = arr[key]);
}
But be careful because this will also loop through the properties of an object, including if you pass in an Array object.
The generalized format of a for loop (not a for-in loop) is
for ( EXPRESSION_1 ; EXPRESSION_2 ; EXPRESSION_3 ) STATEMENT
The first EXPRESSION_1 is usually used to initialize the loop variable, EXPRESSION_2 is the looping condition, and EXPRESSION_3 is usually an increment or decrement operation, but there are no rules that say they have to behave like that. It's equivalent to the following while loop:
EXPRESSION_1;
while (EXPRESSION_2) {
STATEMENT
EXPRESSION_3;
}
The commas are just an operator that combines two expressions into a single expression, whose value is the second sub-expression. They are used in the for loop because each part (separated by semicolons) needs to be a single expression, not multiple statements. There's really no reason (except maybe to save some space in the file) to write a for loop like that since this is equivalent:
shuffle = function(o) {
var j, x;
for (var i = o.length; i > 0; i--) {
j = parseInt(Math.random() * i);
x = o[i - 1];
o[i - 1] = o[j];
o[j] = x;
}
return o;
};
INITIALIZER can declare and initialize multiple variables. STOP CONDITION is a single test (here it's just "i"), and INCREMENTER is an expression to be executed each time after body (the comma operator lets you have multiple sub-expressions, which all get executed. ). The body of the for loop is just the empty statement ";"
The code you quote is obfuscated in my opinion. There are much clearer ways to write the same functionality.
However, your understanding is pretty much right. The following is the exact same code, except for whitespace and comments.
for (
// Initializer
var j, x, i = o.length;
// Continue condition
i;
// Operation to be carried out on each loop
j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x
)
// empty body, equivalent to { }
;
It's much clearer to write the equivalent:
var j,x,i = o.length;
while(i) {
j = parseInt(Math.random() * i);
x = o[--i];
o[i] = o[j];
o[j] = x;
}
There are other optimisations that could be made for readability - including using while(i > 0) instead of while(i), and splitting out the --i into an i-- on a separate line.
There's really no reason for for() to exist, except for readability. These two are equivalent:
{ // this block is to scope int i
int i=0;
while(i<100) {
myfunc(i);
i++;
}
}
for(int i=0; i<100; i++) {
myfunc(i);
}
You should use whichever is most readable for a given time. I'd argue that the author of your code has done the opposite. In fairness, he may have done this in order to achieve a smaller JS file for faster loading (this is the kind of transform an automated code compactor could do).
Syntax of for loop is:
for (pre-block; condition; post-loop-block)
loop-block;
First, pre-block is executed, various variables are defined.
In each loop:
check condition
execute loop-block
execute post-loop-block
repeat from 1.
That statement does comply with your initial format.
It turns out you could add more than one sentence of each using "," ( comma )
So:
for (var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
Could be analyzed like this:
for (var j, //INITIALIZER(s)
x,
i = o.length;
i; // STOP CONDITION ( i )
j = parseInt(Math.random() * i), // INC(DEC)REMENTER
x = o[--i],
o[i] = o[j],
o[j] = x); // CODE ( ; )
As you see, it fits completely in your initial format.
They've pretty much just moved the body of the loop into the incrementer section. You can re-write the for loop as a while loop to get some idea of what it is doing:
shuffle=function(o) {
var j; //Random position from 0 up to the current position - 1
var x; //temp holder for swapping positions
var i=o.length; //current position
while(i>0) { // Loop through the array
j = parseInt(Math.random()*i); //get a lower position
x = o[--i]; // decrement the position and store that position's value in the temp var
o[i]=o[j]; // copy position j to position i
o[j]=x; // copy the temp value that stored the old value at position i into position j
}
return o;
}
The first three var's are the initialzier expanded out, the check in the while is the stop condition and the body of the while is what was done in the incrementer portion of the for.
Edit: Corrected per Gumbo's comment
this goes all the way back to C syntax - from which javascript has stole a bunch. the main trick is the comma-operator which seems to appear in almost no other place except for loops
The first clause initializes any variables you want to use. The second clause is indeed the stop condition. The third clause includes any logic to be executed at the end of each iteration. Multiple statements can be separated by commas.

Categories