Adding a variable outside a function each time the function is called - javascript

I am trying to add up the result of a function, after each time the function is called, here is my code:
function computetime(result) {
var time=0;
var mytravelroute=result.routes[0];
for (i = 0; i < mytravelroute.legs.length; i++) {
time += mytravelroute.legs[i].duration.value;
}
var totalSec = time;
I want to add up the "time" variable, each time the function is called. Right now the "time" variable get over written each time, and I need to capture the value each time.
Any ideas? disclaimer: Prog lvl: peon.

var time=0;
function computetime(result) {
var mytravelroute=result.routes[0];
for (i = 0; i < mytravelroute.legs.length; i++) {
time += mytravelroute.legs[i].duration.value;
}
var totalSec = time;

Looks like you simply need a global variable.
var totalSec;
function computetime(result) {
var mytravelroute=result.routes[0];
for (i = 0; i < mytravelroute.legs.length; i++) {
totalSec += mytravelroute.legs[i].duration.value;
}

You can do this:
function computetime(result) {
computetime.time = computetime.time || 0;
var mytravelroute = result.routes[0];
for (i = 0; i < mytravelroute.legs.length; i++) {
computetime.time += mytravelroute.legs[i].duration.value;
}
}

There are lots of ways to do this. It involves closures. You should read about scoping and closures in javascript. Here is one way to do it.
var tracker = {
time: 0
computetime: function computetime(result) {
var mytravelroute=result.routes[0];
for (i = 0; i < mytravelroute.legs.length; i++) {
tracker.time += mytravelroute.legs[i].duration.value;
}
return tracker.time;
}
}
tracker.computetime(result)

Related

this function cause browser crash

I have written a function that i want to detect the language of the text based on utf-8 encoding.Actualy this function determines the input argumant is english or not.The function work correctly in javascript console but when I use it in a loop ,the browser crashes.
//titles.lenght=>90
function is_eng(title) {
var A = 65;
var z = 122;
title = title.toString();
var eng_chars = 0;
var non_eng_chars = 0;
for (i = 0; i < title.length; i++) {
var c = title.charCodeAt(i);
if (c > A && c < z) {
eng_chars += 1;
} else {
non_eng_chars += 1;
}
}
if (eng_chars > non_eng_chars) {
return 1;
}
return 0;
}
You should add the keyword var before i=0, otherwise i is a global variable. If you use i for the external loop, you have an endless loop.

Javascript syntax issue in code

Can someone tell me why this bit of JavaScript is buggy?
I have HTML also, but I don't want to make this a massive code dump.
<script type = 'text/javascript'>
var playerCards = [];
var dealerCards = [];
function deal() {
var newCard = Math.random() % 12;
var newCard2 = Math.random() % 12;
playerCards += newCard;
playerCards += newCard2;
var counter = 0;
for (var i = 0; i < playerCards.length; ++i) {
counter += i;
}
document.getElementById("playerTotal").innerHTML = counter;
var dCounter = 0;
for (var j = 0; j < playerCards.length; ++j) {
dCounter += j;
}
document.getElementById("dealerTotal").innerHTML = dCounter;
}
</script>
I'm gonna assume this is a silly syntax error someplace, but I can't find it.
I'm guessing that this isn't doing what you expect it to:
playerCards += newCard;
playerCards += newCard2;
Try this instead:
playerCards.push(newCard);
playerCards.push(newCard2);
The first snippet is trying to "add" a number to an array, which doesn't exactly make sense. Through some arcane JavaScript rules, this turns the result into a string.
I'm guessing that you want to concatenate to an array instead.
Math.random returns a number between 0 and 1 - so Math.random() % 12 will probably be zero
var playerCards = [];
playerCards += newCard; //
what are you even trying to do there?
var counter = 0;
for (var i = 0; i < playerCards.length; ++i) {
counter += i;
}
if playerCards had a length, this loop would result in counter having value of 0, 1, 3, 6, 10 .. n(n+1) / 2 - probably not what you intended, but who knows

Function for loops with a different process within the loop

I've got a very similar process that occurs in many places, with one small change. I was wondering what would be the best way to make the code neater. Currently, the process is:
var drawx = 0;
var drawy = 0;
while(drawy < 22){
while(drawx < 10){
if(nextBlock[drawx][drawy] != false){
base[drawx][drawy] = nextBlock[drawx][drawy];
}
drawx++;
}
drawx = 0;
drawy++;
}
Within the while drawx < 10 is where I usually have different things to run, and I'm not sure how I would create a function with a variable process in the middle of it. Is there a way to do this, or should I just create a function that does this process and executes a certain if statement depending on the parameter that was called when running the function?
EDIT: I think I might have not gotten my initial problem across. I want to be able to have a process such as the if statement within the loop to be a variable process while the rest of it to be the same
javascript has first class functions so you can do something like this:
function drawLoop(action) {
var drawx = 0;
var drawy = 0;
while(drawy < 22){
while(drawx < 10){
action(drawx, drawy);
drawx++;
}
drawx = 0;
drawy++;
}
}
And then call it like this:
drawLoop(function(drawx, drawy){
if(nextBlock[drawx][drawy] != false){
base[drawx][drawy] = nextBlock[drawx][drawy];
}
});
And of course, you can change the function you pass to drawLoop to suite your needs.
you could inject a function as a variable to your generic function like
function genericDraw(xValidation) {
var drawx = 0;
var drawy = 0;
while(drawy < 22){
while(xValidation(drawX)){
if(nextBlock[drawx][drawy] != false){
base[drawx][drawy] = nextBlock[drawx][drawy];
}
drawx++;
}
drawx = 0;
drawy++;
}
}
where xValidation is
function someValidation(value) {
return (value < 10);
}
and you call it
genericDraw(someValidation);
for( var drawy = 0 ; drawy < 22 ; drawy++) {
for( var drawx = 0 ; drawx < 10 ; drawx ++) {
if(nextBlock[drawx][drawy] != false) {
base[drawx][drawy] = nextBlock[drawx][drawy];
}
}
}

JavaScript syntax issue

I'm doing "fifteen puzzle" game. I'm only a beginner, so I chose this project to implement. My problem is shuffle algorithm :
function shuffle() {
$('td').empty();
var p = 0;
var f = 0;
do {
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
var rand = arr[Math.floor(Math.random() * arr.length)];
if ($('#' + rand).is(':empty')) {
p = p + 1;
document.getElementById(rand).textContent = p
var f = $('td').not(":empty").length;
} else {}
} while (f < 15)
That works cool, but I've heard that almost 50% of all random shuffle like mine is unsolvable. So I found math formula at wikipedia.org for this game, explaining how you can avoid that.
Here's modified algorithm that doesn't work either. The way I know it is alert stuff: it launches only 2 times instead of 31.
array = [];
function algorithm (){
// alert('works')
for (var c=16; c<17; c++){
document.getElementById(c).textContent = '100';
}
for (var i=1; i<16; i++){
var curId = document.getElementById(i).id;
var curIdNum = Math.floor(curId);
alert('works')
var curIn = document.getElementById(i).textContent;
var curInNum = Math.floor(curIn);
array.push(i);
array[i] = new Array();
for (var j=1; j<15; j++){
var nextId = curIdNum + j; //curIdNum NOT cerIdNum
var nextIn = document.getElementById(nextId).textContent;
//alert('works')
if (nextId < 16){
var nextInNum = Math.floor(nextIn);
if (curInNum > nextInNum){
array[i].push(j)
}
}
}
var sum = 0;
for (var a=0; a<15; a++){
var add = array[a].length;
sum = sum + add;
}
var end = sum + 4;
if (end % 2 == 0){
document.getElementById('16').textContent = "";
}
else {
shuffle();
}
}
}
The question is the same:
What's wrong? Two-dimensional array doesn't work.If you've got any questions - ask.
Just to make it clear: 2 for loops with i and j should make a 2-dimensional array like this [ this is " var i" -->[1,3,4,5,7], this is "var i" too-->[5,7,9,14,15]]. Inside each i there's j. The for loop with var a should count the number of js inside each i. if the number of js is even, the code is finished and shuffle's accomplished, otherwise shuffle should be made once again.
var nextId = cerIdNum + j;
in that fiddle, I don't see this cerIdNum declared & defined neither as local nor as global variable, I suppose that is curIdNum
Please use the below definition of algorithm and let us know if this works. Basically, the alert messages would come only twice, since there were usages of undefined variables. For the purpose of illustration, I have placed comments at where the problem points occured. Due to these problems, your script would stop executing abruptly thereby resulting in the behavior you described.
Oh and by the way - I did not have time to go through the Wiki link provided - hence you will have to verify your logic is correct. However, I have definitely resolved the errors causing the behavior you observed.
As an aside - consider using jQuery, your code will be a lot cleaner...
function algorithm (){
// alert('works')
for (var c=16; c<17; c++){
document.getElementById(c).textContent = '100';
}
for (var i=1; i<16; i++){
var curId = document.getElementById(i).id;
var curIdNum = Math.floor(curId);
alert('works')
var curIn = document.getElementById(i).textContent;
var curInNum = Math.floor(curIn);
array.push(i);
for (var j=1; j<15; j++){
var nextId = curIdNum + j; //curIdNum NOT cerIdNum
var nextIn = document.getElementById(nextId).textContent;
//alert('works')
if (nextId < 16){
var nextInNum = Math.floor(nextIn);
if (curInNum > nextInNum){
array.push(j) //array[i].push does not make sense
}
}
}
var sum = 0;
for (var a=0; a<15; a++){
var add = array.length; //array[1].length does not make sense
sum = sum + add;
}
var end = sum + 4;
if (end % 2 == 0){
document.getElementById('16').textContent = "";
}
else {
shuffle();
}
}
}
I found the solution by totally rewriting the code. Thank everyone for help!
Here's what do work:
function shuffle (){
press = 1;
$('td').empty().removeClass();
p=0;
var f;
do {
var arr=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
var rand=arr[Math.floor(Math.random()*arr.length)];
if ($('#'+ rand).is(':empty')){
p = p + 1;
document.getElementById(rand).textContent = p
var f = $('td').not(":empty").length;
}
else{}
}while(f < 15){
winChance();
}
}
function winChance (){
array = [];
for (i=1;i<16;i++){
array[i]= new Array();
var currentId = $('#' + i).attr('id');
var currentIn = $('#' + i).html()
var currentIdNum = parseInt(currentId, 10);
var currentInNum = parseInt(currentIn, 10);
for (j=1;j<16;j++){
var nextId = currentIdNum + j;
if (nextId < 16){
var nextIn = $('#' + nextId).html();
var nextInNum = parseInt(nextIn, 10);
if (currentInNum > nextInNum){
array[i].push(j);
}
}
}
}
checkSum();
}
function checkSum(){
var sum = 0;
for (var a=1; a<16; a++){
var add = array[a].length;
sum = sum + add;
}
var end = sum + 4;
if (end % 2 == 0){}
else {
shuffle();
}
}

Why this JS function does't not work when it calls by selenium.getEval()

Below js function is working well in html page. But when i put it into selenium.getEval in RC to wonder to get return value j. It cannot work, also without any error. Do i miss some function call format? Thanks in advance!!!
function GetTableRow()
{
var table;
var ctext = "bb";
var cname = "mps_tableborder";
var col = 0;
var j;
for (i = 0; i < document.getElementsByTagName("table").length; i++) {
if (cname==document.getElementsByTagName("table")[i].className) {
table = document.getElementsByTagName("table")[i];
break;
}
}
for (j = 0; j < table.rows.length; j++){
if (ctext == table.rows[j].cells[col].innerText){
break;
}
}
return (j);
}
You can provide only the contents of method. Not the entire method. Try by removing the method starting [ function GetTableRow() { ] and method ending [ } ] and give it to getEval method and see what it returns! Ideally it should work fine.

Categories

Resources