Passing a calculated variable from one function to another - javascript

...not sure "calculated" was the right word...I have written two functions, the second of which needs the output of a variable from the first. I cant seem to get it to pass...my guess is that I am calling it wrong, but can't seem to get it right...might have something to do with the time I've spent staring at the whole thing..
The variable I need passed is subset I am trying to use it on the last line of the second function.
If it matters, the getPos function is getting its value from an input box.
The javascript:
<script>
var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
function getPos(value)
{
var letterPosition = alphabet.indexOf(value);
var subset = alphabet.slice(letterPosition+1, 26);
document.getElementById('theRest').value = subset;
}
function appendTable(id)
{
var tbody = document.getElementById(id).getElementsByTagName("tbody")[0];
var i = 0;
for (var r = 0; r < 4; r++) {
var row = tbody.insertRow(r);
for (var c = 0; c < 4; c++) {
var cell = row.insertCell(c);
cell.appendChild(document.createTextNode(subset[i++]));
}
}
}
</script>

<script>
var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var subset;
function getPos(value)
{
var letterPosition = alphabet.indexOf(value);
subset = alphabet.slice(letterPosition+1, 26);
document.getElementById('theRest').value = subset;
}
function appendTable(id)
{
var tbody = document.getElementById(id).getElementsByTagName("tbody")[0];
var i = 0;
for (var r = 0; r < 4; r++) {
var row = tbody.insertRow(r);
for (var c = 0; c < 4; c++) {
var cell = row.insertCell(c);
cell.appendChild(document.createTextNode(subset[i++]));
}
}
}
</script>
That should do the trick.
Declaring subset before the functions makes it a global var, if you define it with var subset within a function it becomes tied to that function, removing the var makes it use the global var.

Related

Altering find and replace Google Sheets script

I have the following script, though I would like to change it to only find and replace on a specific sheet (Sheet4!A:AB).
How would I go about doing this:
function fandr() {
var ss=SpreadsheetApp.getActiveSpreadsheet();
var s=ss.getActiveSheet();
var r=s.getDataRange();
var vlst=r.getValues();
var i,j,a,find,repl;
find="abc";
repl="xyz";
for (i in vlst) {
for (j in vlst[i]) {
a=vlst[i][j];
if (a==find) vlst[i][j]=repl;
}
}
r.setValues(vlst);
}
I think that pnuts's comment is helpful for your situation. If you are still looking for your solution, how about this answer? You want to find and replace the values in Sheet4!A:AB. If my understanding is correct, I would like to propose 2 patterns. I think that there are several solution for your situation. So please think of this as one of them.
Pattern 1
This modification is a simple modification. It modified the range for retrieving values to Sheet4!A:AB.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var r = ss.getRange("Sheet4!A:AB");
var vlst = r.getValues();
var i, j, a, find, repl;
find = "abc";
repl = "xyz";
for (var i = 0; i < vlst.length; i++) {
for (var j = 0; j < vlst[i].length; j++) {
a = vlst[i][j];
if (a == find) vlst[i][j] = repl;
}
}
r.setValues(vlst);
Pattern 2
In the case of pattern 1, the values retrieved by getRange("Sheet4!A:AB") includes the empty rows. By this, the search speed becomes slow. So in this pattern 2, the data range of "A1:AB" is retrieved using getLastRow().
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName("Sheet4");
var r = s.getRange("A1:AB" + s.getLastRow());
var vlst = r.getValues();
var i, j, a, find, repl;
find = "abc";
repl = "xyz";
for (var i = 0; i < vlst.length; i++) {
for (var j = 0; j < vlst[i].length; j++) {
a = vlst[i][j];
if (a == find) vlst[i][j] = repl;
}
}
r.setValues(vlst);
References :
getSheetByName()
getRange(a1Notation)
getLastRow()
If I misunderstand what you want, please tell me. I would like to modify it.

cannot detect error. Where is the infinite loop occurring?

// JavaScript Document
var person = prompt("GIVE INPUT", "");
var count = 0;
var array = person.split(",");
var freq = [];
var words = [];
//freq.fill(0);
//words.fill("");
//window.alert(freq[0]);
var i = 0, j = 0;
while (array.length > 0) {
var temp = array[0];
while (j < array.length) {
if (temp == array[j]) {
count = count + 1;
array.splice(j, 1);
//console.log(array);
j = 0;
}
else {
j = j + 1;
}
}
freq[freq.length] = count;
count = 0;
words[words.length] = temp;
}
window.alert(freq + "\n" + words);
The problem is that whenever I run it an infinite loop occurs and no output is shown, I cannot find the error please help if possible. This code is for finding the frequency of the words in a input string with words separated by commas. thank u.
You just need to put var i=0,j=0; inside the while !
while(array.length>0)
{var i=0,j=0;
Working fidddle
You're resetting your loop variable j to 0 on each iteration. This condition if(temp==array[j]) never fails so j is always reset to 0, so while(j<array.length) is always true.
After coming out of the inner While loop, you need to reset j to zero. As the incremental value of j is not allowing it to go again inside the inner loop So array.length is not reducing And we are getting an infinite loop.
// JavaScript Document
var person = prompt("GIVE INPUT", "");
var count=0;
var array = person.split(",");
var freq = new Array();
var words = new Array();
//freq.fill(0);
//words.fill("");
//window.alert(freq[0]);
var i=0,j=0;
while(array.length>0)
{
var temp=array[0];
while(j<array.length)
{
if(temp==array[j])
{
count=count+1;
array.splice(j,1);
//console.log(array);
j=0;
}
else
{
j=j+1;
}
}
freq[freq.length]=count;
count=j=0;
words[words.length]=temp;
}
window.alert(freq+"\n"+words);
It's where for is more useful for consistency. You can replace inner while loop by this for loop:
for(j=a.length-1; j>=0; j--)
if(temp==a[j]) {
count=count+1;
a.splice(j,1);
}
Nevertheless, overall complexity of your counting method can be reduced with data structure like map.
Essential part of your script can be reduced to this:
var counter = new Map();
for (i in array)
counter.set(array[i], (counter.get(array[i])||0)+1);
var freq = Array.from(counter.values());
var words = Array.from(counter.keys());

Javascript create multidimensional array

I try to create a 4-dimensional array. I fill it dynamically and use content of it in another function. But the content is empty. Is there error below code?
var datas = []; // day number of a week
for(var i = 0; i < 7; i++) {
var size = 24*60/timeInterval;
datas[i] = [];
for(var j = 0; j < size; j++) {
var size2 = allCoords.length / 2;
datas[i][j] = [];
for(var k = 0; k < size2; k++) {
datas[i][j][k] = [];
}
}
}
I test below example :
function foo1()
{
datas[0][0][0].push(10);
}
function foo2()
{
document.getElementByID('result').innerHTML = datas[0][0][0];
}
I see only ,,,,,,,.
I think the principal problem is that you're getting the element where you want to show your result badly using getElementByID instead of getElementById. Also make sure that your element has innerHTML property to write the result, or alternatively use value.
I write the follow example using <textArea id="result"></textArea> and generating a button which calls foo1();foo2(); onClick an it works for me.
In the sample I use an random value for timeInterval and allCoords.length.
Note also that you want a 4-dimensional array however you're creating a 3-dimensional.
var timeInterval = 60;
var allCoords = { length : 1};
var datas = []; // day number of a week
for(var i = 0; i < 7; i++) {
var size = 24*60/timeInterval;
datas[i] = [];
for(var j = 0; j < size; j++) {
var size2 = allCoords.length / 2;
datas[i][j] = [];
for(var k = 0; k < size2; k++) {
datas[i][j][k] = [];
}
}
}
function foo1()
{
datas[0][0][0].push(10);
}
function foo2()
{
document.getElementById('result').value = datas[0][0][0];
}
<textArea id="result"></textArea>
<input type="button" value="foo" onclick="foo1();foo2();"/>
Hope this helps,

Randomly storing elements from an array into a table

I'm trying to create a simple memory matching game and I'm having trouble assigning one number to each table cell from my cardValues array. My giveCellValue function is supposed to generate a random number then pick that number from the array and give it to one of the table cells but I'm a little over my head on this one and having trouble accomplishing this task.
var countCells;
var cardValues = [];
var checker = true;
var createTable = function (col, row) {
$('table').empty();
for (i = 1; i <= col; i++) {
$('table').append($('<tr>'));
}
for (j = 1; j <= row; j++) {
$('tr').append($('<td>'));
}
countCells = row * col;
};
createTable(3, 6);
for (i = 1; i <= countCells / 2; i++) {
cardValues.push(i);
if (i === countCells / 2 && checker) {
checker = false;
i = 0;
}
}
var giveCellValue = function () {
var random = Math.ceil(Math.random() * cardValues.length) - 1;
for (i = 0; i <= cardValues.length; i++) {
$('td').append(cardValues[random]);
cardValues.splice(random, 1);
}
};
giveCellValue();
console.log(cardValues);
Use
var countCells;
var cardValues = [];
var checker = true;
var createTable = function (col, row) {
$('table').empty();
for (var i = 0; i < col; i++) {
$('table').append($('<tr>'));
}
for (var j = 0; j < row; j++) {
$('tr').append($('<td>'));
}
countCells = row * col;
};
createTable(3, 6);
for (i = 0; i < countCells; i++) {
cardValues.push(i % 9 + 1);
}
var giveCellValue = function () {
var len = cardValues.length, tds = $('td');
for (var i = 0; i < len; i++) {
var random = Math.floor(Math.random() * cardValues.length);
tds.eq(i).append(cardValues.splice(random, 1));
}
};
giveCellValue();
console.log(cardValues);
Demo: Fiddle
Leaving aside the problems that have already been mentioned in the comments above...
If I understand it right, you want to assign each of the numbers in cardValues to a random table cell?
Seems like the problem is with this line:
var random = Math.ceil(Math.random() * cardValues.length) - 1;
What this does is generates a random number once. If you access the variable random at a later time, you're not calling the full line of code again, you're just getting the same value that was calculated the first time. E.g. if the above code runs, spits out '7' as its random number and stores that in random, then every time you go through the for loop, the value of random will always be '7' rather than being re-generated every time - make sense?
Try putting the randomiser inside the for loop - that way it will be run multiple times, generating a new random number every time:
var giveCellValue = function () {
var random;
for (i = 0; i <= cardValues.length; i++) {
random = Math.ceil(Math.random() * cardValues.length) - 1;
$('td').append(cardValues[random]);
cardValues.splice(random, 1);
}
};
Actually, I'd change line 4 above to random = Math.floor(Math.random() * cardValues.length); too which should have the same effect.

How to define a var in an array?

Building my first real app with JS: Black Jack. I was just wondering why my j, q, k, and a var are coming back as undefined.
window.onload = init;
var cards = [2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10,j,j,j,j,q,q,q,q,k,k,k,k,a,a,a,a];
var j = 10;
var q = 10;
var k = 10;
var a = 11;
function init() {
var button = document.getElementById("doIt");
button.onclick = processIt;
}
function processIt() {
var cpu1 = document.getElementById("cpu1");
cpu1.innerHTML = cards[37];
}
Any help would be greatly appreciated.
Because at the moment when you declare cards, those variables (or, rather, their values) are still undefined. Reorder the declarations.
var j = 10;
var q = 10;
var k = 10;
var a = 11;
var cards = [2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10,j,j,j,j,q,q,q,q,k,k,k,k,a,a,a,a];
You're defining them after you use them... You have to define variables before you use them, not after.
In javascript, declarations are processed first but assignment occurs in order. Your code is effectively:
var cards, j, q, k, a;
// Here, all variables exist but none have a value
// When cards is assigned an array, the values of j, q, k and a
// are still undefined.
cards = [2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7,8,8,8,
8,9,9,9,9,10,10,10,10,j,j,j,j,q,q,q,q,k,k,k,k,a,a,a,a];
// Now the rest are given values
j = 10;
q = 10;
k = 10;
a = 11;

Categories