for example, I have code like this:
var test = function() {
return Math.random();
}
var randomNumber = test();
// I want to call test() via the randomNumber variable,
// use this variable on another function or etc...
// for example here
for (var i = 0; i < 5; i++) {
console.log(randomNumber); // and it should be show 4 random numbers
}
Is this possible?
Thanks to advance.
I believe you want to assign the function reference to randomNumber instead of calling the function and assigning its return value.
var test = function() {
return Math.random();
}
// Assign test to randomNumber, but don't call it here
var randomNumber = test;
for (var i = 0; i < 5; i++) {
console.log(randomNumber()); // call it here
}
You could assign the value returned by the function to the variable inside the loop and then display it.
Kinda like the code below
// define function
var test = function() {
return Math.random();
}
// define variable
var randomNumber;
// loop
for (var i = 0; i < 5; i++) {
// invoke function, assign value to variable
randomNumber = test();
// output it to console.
console.log(randomNumber);
}
UPDATE
If you do not want to write code to 'loop' thru your array, you can use a fake array and map the same function to it.
You are not looping thru it yourself but looping thru the array is being performed nonetheless.
// array of fake values
var iterations = [0, 1, 2, 3, 4];
// returns an array of random numbers
console.log(iterations.map(function(elem) {
return Math.random();
}));
Related
I wrote this function:
function randomProduct(num) {
var iter = num;
for (var i = 0; i < iter; i++) {
var rand = recommendedProducts[Math.floor(Math.random() * recommendedProducts.length)];
return rand
}
}
Which is supposed to pull from the recommendedProducts array however many are needed when the function is called. So basically randomProduct(1) would pull 1 and randomProduct(4) would pull 4, etc.
However no matter what number I enter in there when I test is through the console, I always only get 1 array item returned.
console.log(randomProduct(1));
console.log(randomProduct(2));
console.log(randomProduct(3));
console.log(randomProduct(4));
What am I doing wrong?
try this:
function randomProduct(num) {
var iter = num;
var rand ="";
for (var i = 0; i < iter; i++) {
rand += recommendedProducts[Math.floor(Math.random() * recommendedProducts.length)];
}
return rand
}
as #Steve Medley said the result expected to be string. so if recommendedProducts contains some string you should add this string in each iteration of loop to your result and return it after your loop has finished( also this is what i have understood from question)
Try this:
function randomProduct(num) {
var iter = num;
var randomArray = [];
for (var i = 0; i < iter; i++) {
randomArray.push(recommendedProducts[Math.floor(Math.random() * recommendedProducts.length)]);
}
return randomArray.join(); // returns it as a string
}
First you need to append the items to an array using push
Second you need to return outside of the loop, if you retrun from the inside of the loop you break the function after the first iteration.
The return rand take you off the function at the first result.
You can remove the loop, just return the rand, and call the function 4 times.
If you want the function to return array of random numbers, instead of return rand, push the results to new array and return the array when the for loop is done.
In your loop, variable rand will be given the value equal to the value it's last iterations output, you need to return array of objects instead of single object to get desired result.
I have some code that returns the contents of a <div> after you press a button. I need to save the result of this function to an array. So how do I do that?
Here's my code so far:
var numKey = document.getElementsByClassName('num-key');
for (var i = 0; i < numKey.length; i++) {
numKey[i].addEventListener("click", function () {
return this.innerHTML;
});
};
There are a couple of ways to do this. I'm going to give you the simple one just now. First, create a global variable array, then just assign the value to that array instead of returning it:
myArray = [];
var numKey = document.getElementsByClassName('num-key');
var len = numKey.length;
for (var i = 0; i < len; i++){
numKey[i].addEventListener("click",function addToArray(){
myArray.push(this.innerHTML);
}
This is probably an easy question but it's late at night and I can't get my head round this.
here's my code
$(document).ready(function () {
var items = getNumber();
for (var i = 0; i < items.length; i++) {
var test = items[i].action;
test();
}
});
function getNumber()
{
var items = [];
for (var i = 0; i < 5; i++) {
var num = i * 10;
items.push({ id: i, number: num, action: function () { alert(i) } });
}
return items
}
Could someone explain to me why the alert output is always 5? I want the alert parameter to be the index at the time it is added to the array. It seems like it is being dynamic.
If you could also post a solution how i could get this to work i would be extremely thankful
This is a common issue with JavaScript variable scoping: new variables are only introduced in a new execution context and thus, in the problematic code, i is shared across all the action callbacks.
Anyway, here is the corrected code following the standard idiom:
function getNumber()
{
var items = [];
for (var i = 0; i < 5; i++) {
var num = i * 10;
items.push({
id: i, number: num,
// _i is a new variable for each callback
action: (function (_i) {
// use separate (one per callback) _i variable
return function () { alert(_i) }
})(i) // pass in current value for loop
});
}
return items
}
Alternatively, if one doesn't like all the nesting, it's fine to use a "named" function to perform the same task. The key to point is that the closure is created (and returned from) a new execution context so that a different variable is closed-over:
function getNumber()
{
function mkAction (i) {
return function () { alert(i) }
}
var items = [];
for (var i = 0; i < 5; i++) {
var num = i * 10;
items.push({
id: i, number: num,
action: mkAction(i)
});
}
return items
}
Another approach is to use Function.bind from ES5:
function getNumber()
{
var items = [];
for (var i = 0; i < 5; i++) {
var num = i * 10;
items.push({
id: i, number: num,
action: (function (_i) { alert(_i) }).bind(null, i)
});
}
return items
}
(Note that Function.bind can be emulated using a new execution context/closure even without native browser support. See the MDC documentation.)
See also:
JavaScript closure inside loops – simple practical example
Passing functions to setTimeout in a loop: always the last value?
How do JavaScript closures work?
So my basic setup is this:
for (var i = 0; i < 3; i++) {
var indices = [-1, -1, -1];
while (index == -1) {
// Do Stuff
index[i] = newIndex;
}
var press = function() { alert(i); };
new control({press: press});
}
Now when I press the each of the new controls instead of getting alert(0), alert(1) and alert(2) I get alert(3), alert(3) and alert(3).
I can kind of understand whats going on. Now my question: how can i pass the different indexes to the function as I intended?
It is because closure variable i, the solution is to create a private closure for each loop.
for (var i = 0; i < 3; i++) {
var indices = [-1, -1, -1];
while (index == -1) {
// Do Stuff
index[i] = newIndex;
}
var press = (function(myvar){
return function() { alert(myvar); };
})(i);
new control({press: press});
}
Use closure:
var press = (function (x) {
return function () {
alert(x);
};
})(i);
This way the current i value is saved in a safe place, a private function.
Note that declaring variables (with var) inside loops are not standard, you should declare the press variable outside the loop.
I have a for loop that needs to return something on every iteration:
for(var i=0;i<100;++i) {
return i;
}
but return breaks the loop. How can I return but kee the loop running?
Store it inside an array.
var array = [];
for (var i = 0; i < 100; ++i) {
array.push(i);
}
The context here is unclear. If you are trying to execute a function for each iteration of the loop, why not something simple like calling a function from within the loop?
for(var i=0;i<100;++i) {
processIteration(i)
}
In processIteration you could simply handle what you need to happen with that value.
Store the values you need to return in an array, then after the loop, return the array.
There are 3 ways to solve this
Promises
function loop() {
promises = []
for (var i = 0; i < 100; ++i) {
// push a promise resolve to a promises array
promises[i] = Promise.resolve(i);
}
return promises;
}
// Observe the promises loop
for (let p of loop()) {
p.then(console.log)
}
Callbacks
function loop(cb) {
for(var i = 0; i < 100; ++i) {
// calling the callback
cb(i);
}
}
// Pass a do something method
// Here it's the console log as the callback
loop(console.log)
Yield
// Generator function for loop over 100
function* loop() {
for (var i = 0; i < 100; ++i) {
// return value from loop
yield i;
}
}
// Initialize the generator function
let it = loop();
// Call and get the resulr
// it.next().value
var result = it.next();
while (!result.done) {
console.log(result.value); // 1 2 3 .... 99
result = it.next();
}