If I have a funtion like this:
function xyz(b)
{
for(var i = 0; i < b.length; i++)
{
// do something with b items...
}
}
... wouldn't it be more memory-friendly if I were to assign b to a local variable inside of that function before working with its items?
function xyz(b)
{
var c = b;
for(var i = 0; i < c.length; i++)
{
// do something with c items...
}
}
In your example both b and c are local variables since they only exist in the function. So your code will actually be a bit less performant.
Side note - if you want your code to be more performant you should calculate c.length only once for the whole for loop. In your example you're calculating it for every iteration of the loop. Instead you can do as follows:
for (var i = 0, cLen = c.length; i < cLen; i++)
This way it calculates it only once before starting the loop.
Related
How to create the np.eye function in JavaScript? Or what would be the numpy.eye equivalent in JavaScript?
I would like a function that creates the "Identity matrix" in 2d dimensions, and you can change the number of rows, columns and the index of the diagonal.
https://numpy.org/devdocs/reference/generated/numpy.eye.html
This doesn't take care of M,N,k
#Andy
function eye(n){
var t=[];
for(var i=0;i<n;i++){
var p=[]
for(var j=0;j<n;j++){
p.push(j==i?1:0)
}
t.push(p)
}}
This doesn't take care of M,N,k
You are almost there, just have to put the extra parameters there, like the outer loop (rows) runs to N, the inner loop (columns) runs to M, and the comparison would be j-i===k:
function eye(N,M,k) {
var t = [];
for (var i = 0; i < N; i++) {
var p = []
for (var j = 0; j < M; j++) {
p.push(j - i === k ? 1 : 0)
}
t.push(p)
}
return t;
}
let NMk=prompt("N,M,k").split(",").map(x=>parseInt(x));
console.log(eye(...NMk).map(x=>x.join()));
Try entering something like 3,3,0 ("classic") or 2,3,1 (a "fancy" one) when asked.
(And don't worry about the snippet printing strings, that's just the join() , to keep output small, and without much coding).
I am trying to keep a for loop variable after its execution, since the condition will be changing through another for loop. Here's my exemple:
l = 0;
for (var i = 0;i<5:i++){
for(var l; l<l+i;l++){
}
}
My goal here is to remember the value of l when I'm leaving the for loop, and keep it for the next execution with the new condition. I understand this is vague but any help is appreciated.
Just use a while loop:
var l = 0;
for (var i = 0;i<5:i++){
while(l < l+i) {
// do stuff
l++;
}
// Here you have the value of l when breaked out of the loop
}
Your code already works as expected, the var l declares the variable in the outer scope so that you can access it outside of the loop.
You will however need to fix the typo (:->;) and the infinite loop (l<l+i is always true for positive i), and I'd recommend to put the var declaration on the first initialisation of the variable:
var l = 0;
for (var i=0; i<5; i++) {
var end = l+i;
for (; l<end; l++) {
console.log(i, l);
}
}
The other answers will work, however you have no reason to be using var in 2019, and they also don't effectively take advantage of the for loop syntax.
let l = 0;
for (let i = 0; i<5; i++){
for(; l < i + 1; l++){
}
}
console.log(l); // 5
This example maintains the value of l through the outer loop's iterations and then also keeps it at the end.
var l = 0;
for (var i = 0;i<5:i++){
for(l; l<l+i;l++){
}
}
Will let you retain the latest value for l. By the way, without using a break I suspect that this will result in an infinite loop, since l will always be less than l+i (when i is not 0).
Edit: loop not recursion
Wondering if there is by any chance to programmatically setting third statement of forloop
var conditionProgrammatically = 'i++';//or 'x--'
for (var i = 0; i < 10; conditionProgrammatically) {
console.log(i)
}
You can use any expression you want there including calling a function. You just need to be careful of scope. So, for example, this works:
var conditionProgramatically = () => i++ ;
for (var i = 0; i < 10; conditionProgramatically()) {
console.log(i)
}
But it depends on the fact that var i is in a scope shared by the function. This, however, doesn't work:
var conditionProgramatically = () => i++ ;
for (let i = 0; i < 10; conditionProgramatically()) {
console.log(i)
}
Because let is scoped to the block and not available.
Of course you can share an object which is mutable by passing it as an argument like:
fn = (o) => o.i += 1
for (let o = {i:0}; o.i < 10; fn(o)) {
console.log(o.i)
}
This allows you to use let, but is a little hard on the eyes.
All said, it's probably going to be easier to make your logic fit in a simple expression rather than calling a function. You can still perform some logic, though:
for (let i = 0; Math.abs(i) < 10; i = Math.random() > .65 ? i -1: i + 1) {
console.log(i)
}
You can set a variable and then operate with this variable according to your needs.
(remember that i-- is equivalent to i -= 1).
BTW, be careful because you would also have to change the condition, if not you will end up in an infinite loop. In your case, I would use abs()
var step = 1; // or var step = -1;
for (var i = 0; abs(i) < 10; i += step) {
console.log(i)
}
Usually, in functional programmings (like python and javascript), we can use dictionary (or objects) to store functions.
var myFunctions = {
"a": function (i) { return i + 1 },
"b": function (i) { return i - 3 }
};
Then, we can set the condition as the key to the dictionary:
myCondition = "a"; // this will set condition to increment by 1
Here is your for loop:
for (i = 0; i < n; i = myFunctions[myCondition](i)) {
// whatever
}
Looking at http://es6-features.org/#BlockScopedVariables
What a difference between
for (let i = 0; i < a.length; i++) { let x = a[i] … }
and
for (var i = 0; i < a.length; i++) { var x = a[i] … }
I understand in example they move declaration of variables out of block
var i, x, y
for (i = 0; i < a.length; i++)
{
x = a[i] …
}
but is there any reason for it ? why not to include declaration inside the block ? Is it a bad practice or performance hit ?
Just want to understand.
Thanks.
Block scoped variables are simply not available outside their containing block. This is easy to illustrate with an example
for (let i = 0; i < 2; i++) console.info('inner loop i', i);
try {
console.info('after loop i', i);
} catch (e) {
console.error(e.message)
}
for (var j = 0; j < 2; j++) console.info('inner loop j', j);
console.info('after loop j', j);
The primary difference is scope.
Before ES6, you were stuck using var. When using var, variables were defined in the scope of the enclosing function. If there is no function, then they are defined on the global object (typically window). This made it difficult to have two variables named the same, but in different scopes without running into conflicts.
let helps to solve this problem by allowing you to scope variables to the enclosing block, like an if or for loop.
For example, one common issue was nested for loops:
for(var i = 0; i < 4; i++){ // loop 1
console.log(i); // 0
for(var i = 0; i < 4; i++){ // loop 2
}
console.log(i); // 4 - since i was changed by loop 2, loop 1 is now unstable and will skip
}
In the example above, the problem is eliminated using let instead - each i variable is scoped to it's own block.
As for any differences in performance, I can't say. If someone else knows, I'd love to know.
I am confused about how to iterate on multiple values.
for example : values.categories[0].num[0].entry[0].label;
Do I need to write three for loops in order to iterate through categories, num and entry.
Because categories[0] will always identify the 1st position, but am looking for generic categories[i].
Can you please help me out whether to write three for loops or better option is there to achieve.?
This is what I have tried:
var result = [];
for (var i = 0; i < categories.length; i++) {
var abc = categories[i].num;
for (var j = 0; j < abc.length; j++){
var def = num[i].entry;
}
for(var k = 0; k < def.length; k++){
var ghi = entry[i].label;
result.push(ghi)
console.log(result);
}
}
you can use the each function of jquery.
$.each(categories, function(ci, num) {
// This set the index of the array in ci and the value in num = categories[ci]
$.each(num, function(ni, entry) {
// etc ...
});
});
if you want it to stop the iteration you can return false inside the callback function.