I'm trying to do a simple JS loop where I initialize a variable with a value outside the loop, but for some reason its not working.
Basically, I'd like to have total_money equals to 20 in my example, but it keeps returning money
var total = 0;
var money = 20;
var ticker = ['money'];
for (tick in ticker) {
total_money = ticker[tick];
}
console.log(total_money);
Remove the single-quotes '...' from your array called ticker:
var total = 0;
var money = 20;
var ticker = [money]; // <-- Remove the single-quotes
for (tick in ticker) {
total_money = ticker[tick];
}
console.log(total_money);
I know this is a simplified version of the code, but just be aware that you are not adding up total_money but overwriting
So if you have another ticker. For example:
var total = 0;
var money1 = 20;
var money2 = 30;
var ticker = [money1,money2];
for (tick in ticker) {
total_money = ticker[tick];
}
console.log(total_money);
You will get total_money = 30, not 50.
You can fix this by doing total_money += ticker[tick]
Also note that you are looping through one item.
The reason is because:
for (tick in ticker) {
console.log(tick) //tick equal 0
}
Related
function randomNumber(){
var value;
var flag = false;
var tds = document.querySelectorAll('td');
do{
value = Math.round(Math.random() * (26 - 1) + 1);
for(var t = 0; t < tds.length; t++){
if(tds[t].innerHTML == value)
flag = true;
}
if(!flag){
return value;
}
}while(flag == true)
}
This function returns a random number for innerHTML of a new td. In case there are other tds with the same number as this code generates, the loop starts once again. If the generated number is unique, I add it to the innerHTML of a new td. But I can't even load the page since I run into an infinite loop, but no matter how hard I tried, I couldn't notice the problem in logic of this code.
As soon as your loop find the case where tds[t].innerHTML == value it sets flag to true - at this point you can never end the loop because nowhere do you check for a case where you can set flag to false, so your loop condition will always be true.
Here's a similar example that illustrated this with an array. You can see that sometimes it adds numbers to the array (in the case where it finds a new value) but other times the loop hits 5000 iterations an exits (because it never finds a new value), in which case it adds undefined to the array, since the function hasn't returned anything.
const arr = []
function randomNumber(){
var value;
var flag = false;
var tds = arr
var iterations = 0
do {
value = Math.round(Math.random() * (26 - 1) + 1);
for(var t = 0; t < tds.length; t++){
if(tds.includes(value))
flag = true;
}
if(!flag){
return value;
}
iterations += 1
console.log(iterations)
} while(flag == true && iterations < 5000)
}
for (let i = 0;i<20;i+=1) {
arr.push(randomNumber())
}
console.log(arr)
The moment your function at least once set the flag to true, its over - it never sets it to false again. To fix it i added one line of code.
function randomNumber(){
var value;
var flag = false;
var tds = document.querySelectorAll('td');
do {
flag = false; // this line i added
value = Math.round(Math.random() * (26 - 1) + 1);
for(var t = 0; t < tds.length; t++){
if(tds[t].innerHTML == value)
flag = true;
}
if(!flag){
return value;
}
}while(flag == true)
}
I will also write a bit more efficient code for you
function randomNumber(){
var value;
var found = false;
var tds = document.querySelectorAll('td');
var existingIds = [];
tds.forEach(td => existingIds.push(td.innerHHML)); // fill up the ids
do {
value = Math.round(Math.random() * (26 - 1) + 1); // this line would make problems (comment below)
if (existingIds.indexOf(value) === -1) found = true; // check if value can be found in existing ids and if found - set dount to true (you can also return from here, but i would rather user break (if there was more code after this line, than use retur in the middle of any loop;
} while(found === false)
return value;
}
Comment for line with random:
random() returns number from 0 to 1
as you wrote it - that value would be random number between 1 and 26 (only this values).
if all of the values are already used then our loop will be not ending (we could never find value between 1 and 26 that is not used, when all values from 1 to 26 are already used.
What can be done
You can add some counter (as #Ben did) and exit the loop in that case.
Or you can raise the number 26 to much higher
You can use consecutive numbers (get all, take the max one, add 1 and return this as new number)
You can of course find some other ways to counter that
I'm building a game currently but I have a small problem with keeping the score. Basically I have an textfield that gets a random word input, then if someone clicks on the field or symbol containing the field then I want to check the random word input, if it's a correct word I want to update score textfield, if it's incorrect I want to update errors textfield.
For this I am using an if/else construction, the problem I have with it is that in my game every click only goes either in the if statement or if I change code then only the else, but it's not checking symbol for symbol, every time I click to see if it's an correct word or not. Here is the code I am using on the symbol.click symbol. My question is, am I doing anything wrong in the if/else statements or are my variable calling methods wrong. I have source files on request.
symbol.click:
var y = sym.getVariable("lijst");
var x = "bommen";
// if variables are a match then update score with 1
if (sym.getVariable("x") == sym.getVariable("y"))
{var score3 = sym.getComposition().getStage().getVariable("score1");
score3= score3 +=1;
sym.getComposition().getStage().$ ("scoreTxt").html(score3);
sym.getComposition().getStage().setVariable("score1", score3);
}
// else update error textfield with 1
else {
var fouten= sym.getComposition().getStage().getVariable("fouten1");
fouten= fouten +=1;
sym.getComposition().getStage().$ ("hpTxt").html(fouten);
sym.getComposition().getStage().setVariable("fouten1", fouten);
}
symbol.creationComplete
var words = ['bommen',
'dammen',
'kanonnen',
'dollen',
'bomen',
'feesten',
'lampen',
'voeten',
];
var lijst = words[Math.floor(Math.random() * words.length)];
sym.$("dynamicText").html(lijst);
//And my stage:
stage.creationComplete
// some different variables declarations
sym.setVariable("score1", 0);
sym.setVariable("fouten1", 0)
//var game = sym.getComposition().getStage();
var cirkels = [];
var test1 = "bommen";
var score2 = sym.getComposition().getStage().getVariable("score1");
var fouten = sym.getComposition().getStage().getVariable("fouten1");
var cirkelStart = {x:180,y:190};
var cirkelSpacing = {x:170,y:170};
function init(){
initPlayer();
spawnCirkels();
}
//this is for score and error updating
function initPlayer(){
sym.$("scoreTxt").html(score2);
sym.$("hpTxt").html(fouten);
}
// create symbols on a grid
function spawnCirkels(){
var cirkel;
var el;
var i;
var xPos = cirkelStart.x;
var yPos = cirkelStart.y;
var col = 0;
for(i = 0;i < 15;i++){
cirkel = sym.createChildSymbol("Cirkel", "Stage");
cirkel.play(Math.random() * 1000);
cirkels.push(cirkel);
el = cirkel.getSymbolElement();
el.css({"position":"absolute", "top":yPos + "px", "left":xPos + "px"});
xPos += cirkelSpacing.x;
col++;
if(col === 5){
col = 0;
yPos += cirkelSpacing.y;
xPos = cirkelStart.x;
}
}
}
init();
If anyone sees what I am doing wrong let me know!
Thanks for your help anyway!
I'm attempting to generate 10 random numbers 3 times and capture the hi, the lo, and last in every 10 number batch. I create an array of the hi/lo/last that gets pushed into another array so I can keep track of the numbers. Unfortunately the push command below seems to be only adding the last hi/lo/last 3 times, instead of each hi/lo/last. Not sure what I'm doing wrong.
Also, I clearly am not an expert programmer having worked mostly with VBA in excel where I could step through a program. Is there any way to do that in Sublime with Javascript? I'm working in a windows environment, using Sublime Text 2, with a Node build for Javascript.
Thanks in advance for the help.
var price;
var hiPrice;
var loPrice;
var intervalPrices = []
var initialPrices = [];
var rows = 3;
var columns = 3;
var randomPrices = function(){
price = 1
hiPrice = price
loPrice = price
for (var i = 1; i <= 30; i++){
price = Math.round((price+(Math.random()*2-1)/1000)*100000)/100000
priceIs()
if (i%10 == 0){
intervalPrices[0] = hiPrice
intervalPrices[1] = loPrice
intervalPrices[2] = price
initialPrices.push(intervalPrices)
hiPrice = price
loPrice = price
}
}
}
var priceIs = function(){
if (price >= hiPrice) {
hiPrice = price
}
if (price < loPrice) {
loPrice = price
}
}
randomPrices()
console.log(initialPrices)
Try making separate object or make it clone instead of original object.
initialPrices.push([intervalPrices[0], intervalPrices[1], intervalPrices[2]])
Now
console.log(JSON.stringify(initialPrices))
[[1.00092,0.99835,0.99906],[0.99906,0.99758,0.99762],[0.99907,0.99734,0.99907]]
Its just a prob of variable reference whenever you edit intervalPrices it will override prev value of intervalPrices. Pushing same variable with different value will not preserve the value already pushed to the array as every element of that array points to the same intervalPrices variable.
your updated code - read comment for better understanding
var randomPrices = function(){
price = 1
hiPrice = price
loPrice = price
for (var i = 1; i <= 30; i++){
//create a new Object
var obj = {};
price = Math.round((price+(Math.random()*2-1)/1000)*100000)/100000
priceIs()
if (i%10 == 0){
//assing new values to the Object
obj[0] = hiPrice
obj[1] = loPrice
obj[2] = price
initialPrices.push(obj)
hiPrice = price
loPrice = price
}
}
}
Using the same variable name to build the array you're trying to push is causing you your issues. Try this instead:
for (var i = 1; i <= 30; i++) {
price = Math.round((price+(Math.random()*2-1)/1000)*100000)/100000;
priceIs();
if (i%10 == 0){
initialPrices.push([hiPrice,loPrice,price]);
hiPrice = 1;
loPrice = 1;
}
}
I also set hiPrice and loPrice back to 1 rather than the random number that was generated.
Im trying to get the total combined value of a set of numbers.
Im getting the numbers as the text in an element tag storing them in an array then adding them all together. My problem is that its not inserting the numbers into the array as pairs.. it adding them as single integers .what am doing wrong.
check the jsfiddle too see example
http://jsfiddle.net/Wd78j/
var z = $('.impressions').text();
var x = [];
for(var i = 0; i < z.length; i++){
x.push(parseInt(z[i]));
}
console.log(x);
var total = 0;
$.each(x,function() {
total += this;
});
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");
When you get text, it's taking all the numbers and concatenating them into a string. The below takes each element one at a time and pushes it.
var x = [];
$('.impressions').each( function( ) {
var z = $(this).text();
x.push(parseInt(z, 10));
})
Of course, you could build the sum up inside that each function, but I did it like this to more closely mirror your code.
text() returns the concatenated text of all of your impressions elements, of which you're adding together each character.
You want to loop through each impressions element, and keep a running sum going. Something like this should work
var sum = 0;
$('.impressions').each(function(){
sum = sum + (+$(this).text());
});
Updated Fiddle
Or to keep your original structure (don't forget the radix parameter to parseInt):
var z = $('.impressions');
var x = [];
z.each(function(){
x.push(parseInt($(this).text(), 10));
});
console.log(x);
var total = 0;
$.each(x,function() {
total += this;
});
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");
Updated fiddle
You are iterating over a string, you could just use $.map to build the array instead, if you need it, otherwise just iterate and sum up the values :
var x = $.map($('.impressions'), function(el,i) {return parseInt($(el).text(), 10);}),
total = 0,
n = x.length;
while(n--) total += x[n] || 0;
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");
FIDDLE
I have a bunch of testimonials for my site which are currently on a page and am trying to get a div to display each 1 at an interval of 5 seconds, if the array reaches the last value it should start back to beginning of the array again.
Here is what I have so far...
var testimonial = new Array();
testimonial[1] = "Rugby";
testimonial[2] = "Baseball";
testimonial[3] = "Cricket";
var length = testimonial.length
var i = 1;
setInterval(function() {
while (i <= length) {
$('#testimonials p').html(testimonial[i]);
++i;
if (i == length) {
i == 1;
}
}
}, 5000);
Any help would be great, thanks.
Try
var testimonial = ['Rugby', 'Baseball', 'Cricket'];
var numTestimonials = testimonial.length;
var index = 0;
setInterval(function() {
$('#testimonials p').text(testimonial[index]);
index = (index + 1) % numTestimonials;
}, 5000);
JavaScript arrays are 0-indexed and have handy array literal syntax. Using the modulus operator (%) is an idiomatic way of wrapping a counter back to 0 once it reaches a certain value.
You can try
setInterval(function() {
$('div').html(test[ (i = (i + 1) % length) ]) },
5000);
The function in setInterval is being called every 5 seconds. That means you display the 5 testimonials one after another really quick every 5 seconds instead of displaying them one after the other.
You should do something like:
var testimonial = new Array();
testimonial[1] = "Rugby";
testimonial[2] = "Baseball";
testimonial[3] = "Cricket";
var length = testimonial.length
var i = 0; // arrays start with 0
setInterval(function() {
$('#testimonials p').html(testimonial[i]);
i++;
if (i == length) i = 0;
}, 5000);
Many interesting answers, so one more won't hurt. :-)
You can bundle it all up in an immediately called function expression:
(function() {
var testimonials = ['Rugby', 'Baseball', 'Cricket'];
var i = 0;
setInterval(function() {
$('#testimonials p').text(testimonials[++i % testimonials.length]);
}, 5000);
}());