I am pushing some functions into an array but I am not sure how to run the functions as I loop through the array.
I am trying to get red yellow green to output to the console.
Here is a fiddle to my JavaScript: http://jsfiddle.net/rYNv4/
Here is the code that I have so far as well:
var myArr = [];
myArr.push( logItRunner('red') );
myArr.push( logItRunner('yellow') );
myArr.push( logItRunner('green') );
console.log(myArr);
//Function to be stored in array. Should return the logIt function.
function logItRunner( arg ) {
return function() {
logIt( arg );
};
}
//Function to log a string to the console
function logIt (color) {
console.log(color);
};
//Function to loop through array and fire functions within the array
function runIt () {
for (var i = 0, len = myArr.length; i < len; i++) {
//Fire Function within Array at position i and log the argument to the console.
myArr[i];
};
};
runIt();
myArr[i] is a function reference. You call the function it refers to just like you do any other time you have a function reference, with ():
In your loop, change:
myArr[i];
to
myArr[i]();
See how I'm executing the myArri; below.
You've almost got it, you just forgot the ().
//Function to loop through array and fire functions within the array
function runIt () {
for (var i = 0, len = myArr.length; i < len; i++) {
//Fire Function within Array at position i and log the argument to the console.
myArr[i]();
};
};
It is all about how JavaScript closures work, this usually is the way we teach JavaScript closures, so your sample is a good one, since it clarifies the concept.
This is the way I usually do the exact same thing to teach JavaScript closures, which is completely similar to yours with some little differences:
var myArr = [];
myArr.push('red');
myArr.push('yellow');
myArr.push('green');
var funcArr=[];
function pushIt () {
for (var i = 0, len = myArr.length; i < len; i++) {
var func = (function(color){
return (function(){
console.log(color);
});
})(myArr[i]);
funcArr.push(func);
};
};
function runIt () {
for (var i = 0, len = funcArr.length; i < len; i++) {
funcArr[i]();
};
};
pushIt();
runIt();
Related
I'm trying to store a value from a parameter to an array. Unfortunately, when I'm trying to push a value, it also changed the former value. So in the end, they all have same value but it shouldn't.
For example: I push "1". It store, but when I push "2", it replaced the "1"
Here is my code:
function Add(num) {
var numArr = [];
var count= 10;
for (var i = 0; i < count; i++) {
numArr.push(num);
}
console.log(numArr);
}
Make the array global, when it is inside the function, whenever the function is called a new array is created. when array is global this problem does not arises
var numArr = [];
function Add(num) {
var count = 10;
for (var i = 0; i < count; i++) {
numArr.push(num);
}
console.log(numArr);
}
Add(11)
Add(112)
The reason why the previous value is replaced is that with each function call you declare your array all over again, with no values in it var numArr = []. Move this definition outside this function and it should be just fine
var numArr = [];
const Add = (num) => {
var count= num;
for (let i = 0; i < count; i++) {
numArr.push(num);
}
return numArr
}
console.log(Add(10))
The problem is because you instantiate the array in every iteration of the loop. The simple fix is to pass the array in to the Add() function.
function Add(arr, num) {
var count = 10;
for (var i = 0; i < count; i++) {
arr.push(num);
}
}
var numArr = [];
Add(numArr, 999);
console.log(numArr);
You could alternatively declare the array outside of the function, but this ties the function logic to external variables which makes the point of the function entirely moot.
Also note that the function itself can be replaced with the Array.fill() method which does exactly the same thing, but is unsupported in IE:
var arr = new Array(10);
arr.fill(999);
console.log(arr);
The problem is you create new array when push new value.you can create global array and push value on it.
<script>
_glb_arr=[];
$(document).ready(function (){
Add(1);
Add(3);
console.log(_glb_arr);
});
function Add(val){
_glb_arr.push(val);
}
</script>
I'm pretty sure this is a basic question but my PHP background is making me unable to solve this. I was also unable to find a solution that came even close in SO.
I have an array of objects containing a value I want to loop and sum. Everything works well but I would like to directly sum those values to another array in the output.
So this is the working function:
function postsCalc(arrayEntry) {
var postsOutput = [];
var postLikes = 0;
for (var i = 0, len = arrayEntry.length; i < len; i++) {
postLikes += arrayEntry[i].likes.summary.total_count;
}
postsOutput.likes = postLikes;
return postsOutput;
}
Output:
likes : 55555;
Which works well, but can't I push it directly to the array key and avoid having to do the postsOutput.likes = postLikes?
Like this:
function postsCalc(arrayEntry) {
var postsOutput = [];
for (var i = 0, len = arrayEntry.length; i < len; i++) {
postsOutput.likes += arrayEntry[i].likes.summary.total_count;
// or even a multidimensional:
postsOutput.totals.likes += arrayEntry[i].likes.summary.total_count;
}
return postsOutput;
}
and that would output the same as above but avoiding the extra step, is this possible in Javascript?
Thanks in advance
You can use the reduce function on a list to do this:
function postsCalc(arrayEntry) {
var postLikes = arrayEntry.reduce(function(a, b) {return a + b.likes.summary.total_count}, 0);
return {likes: postLikes};
}
It works like this: Array.reduce(callback, initialValue) where callback = function(a, b) where a is the accumulator (e.g. tracks the sum, etc) and b is a representation of the item you're iterating over on the list. initialValue is the starting point for the function (e.g. on the first iteration).
Idiomatic javascript would look like (for your first function):
function postsCalc(arrayEntry) {
var postsOutput = {
postLikes: 0
};
for (var i = 0, len = arrayEntry.length; i < len; i++) {
postsOutput.postLikes += arrayEntry[i].likes.summary.total_count;
}
return postsOutput;
}
or, now that we can assume .forEach exists:
function postsCalc(arrayEntry) {
var postsOutput = {
postLikes: 0
};
arrayEntry.forEach(function(entry) {
postsOutput.postLikes += entry.likes.summary.total_count;
}
return postsOutput;
}
I'm a newbie in JavaScript. I'm scratching my head because of these two samples I've just made.
function main() {
var arr = [];
for(var i=1; i<=10; i++) {
var x = arr.push(i);
return x;
}
}
console.log(main());
vs
function main() {
var arr = [];
for(var i=1; i<=10; i++) {
var x = arr.push(i);
console.log(x);
}
}
main();
The second one outputs 1-10 in the console, but the first one outputs only 1. Why is the first one (that uses return) not working similarly with the second one (that directly outputs when the function is called)? Is there a solution for the first one?
Because it exits the function at the return statement.
But if you add the return at the end it will give back an array.
function main() {
var arr = [];
for(var i=1; i<=10; i++) {
arr.push(i);
}
return arr;
}
console.log(main());
In x was only saved the length of the array after the push
Here's what is happening in your code:
function main() {
var arr = [];
for(var i=1; i<=10; i++) {
var x = arr.push(i);
return x;
}
}
console.log(main());
Not only in JS but probably in all C-based programming languages, the keyword return exists your current function call. So what happens here is you get in the function, i becomes 1 then with return you explicitly tell the function to stop and display the current value of i.
In the second version, you just console.log() the variable you want written, and that does not interfere with the function in any way, letting it run until the for loop is through.
You can find out a bit more about this behavior here.
I'm trying to implement a duplicate method to the js Array prototype which concats a duplicate of the array to itself like so:
[11,22,3,34,5,26,7,8,9].duplicate(); // [11,22,3,34,5,26,7,8,9,11,22,3,34,5,26,7,8,9]
Here's what I have, but it causes the browser to crash:
var array = [11,22,3,34,5,26,7,8,9];
Array.prototype.duplicate = function() {
var j = this.length;
for(var i = 0; i < this.length; i++) {
this[j] = this[i];
j++;
}
return this;
}
I'm trying to do this using native JS as practice for iterations and algorithms so I'm trying to avoid built-in methods, if possible, so that I can get a clearer understanding of how things are being moved around.
Any ideas on why it is crashing and how I can optimize it?
The code inside the loop changes the length of the array, so it will just keep growing and you will never reach the end of it. Get the initial length of the array in a variable and use in the loop condition. You can use that as offset for the target index also instead of another counter:
var array = [11,22,3,34,5,26,7,8,9];
Array.prototype.duplicate = function() {
var len = this.length;
for (var i = 0; i < len; i++) {
this[len + i] = this[i];
}
return this;
}
The length of the array is increasing with each element added so you can not use this as a terminator. Try this.
var j = this.length;
for(var i = 0; i < j; i++) {
this[i+j] = this[i];
}
Here's simplest code
Array.prototype.duplicate = function () {
var array = this;
return array.concat(array);
};
Using Spread syntax;
In a method, this refers to the owner object.
Array.prototype.duplicate = function () {
return [...this, ...this]
};
let array = [1,2,3,4,5];
Array.prototype.duplicate = function () {
return [...this, ...this]
};
console.log(array.duplicate());
I found this piece of code which seems pretty cool. I see return new Set(array); written so i know set is a class. But what does Set[proto] mean and what does [push] mean and .pop and why is
one a dot while the other is in square brace.
Also arguments[length] looks pretty cool. I imagine its an implicit parameter in each func? i am not sure how length works in this case. This looks really cool and i am very much a newbie at JS.
// Set
var Set = function (items) {
this.items = [];
this[length] = 0;
this.type = "set";
if (items) {
for (var i = 0, ii = items[length]; i < ii; i++) {
if (items[i] && (items[i].constructor == Element || items[i].constructor == Set)) {
this[this.items[length]] = this.items[this.items[length]] = items[i];
this[length]++;
}
}
}
};
Set[proto][push] = function () {
var item,
len;
for (var i = 0, ii = arguments[length]; i < ii; i++) {
item = arguments[i];
if (item && (item.constructor == Element || item.constructor == Set)) {
len = this.items[length];
this[len] = this.items[len] = item;
this[length]++;
}
}
return this;
};
Set[proto].pop = function () {
delete this[this[length]--];
return this.items.pop();
};
In that code the proto variable is set to the string "prototype", and the push variable is set to "push". So, Set[proto] is the same as saying Set.prototype.
So this:
Set[proto][push]
is the same as:
Set.prototype.push
The code is actually creating a function on the Set's prototype called push. A functions prototype is an object that all instances constructed from that function inherit.
For more information about prototype property read this