Javascript: array.push is undefined - javascript

I have my code:
var name = [];
var mark1 = [];
var mark2 = [];
var mark3 = [];
var total = [];
count = 0
count2 = 0
var i = 0;
while (count != 2) {
var nam = prompt("Enter name:")
name.push(nam);
var mk1 = prompt("Enter mark 1:");
var mk1 = parseInt(mk1);
mark1.push(mk1);
var mk2 = prompt("Enter mark 2:");
var mk2 = parseInt(mk2);
mark2.push(mk2);
var mk3 = prompt("Enter mark 2:");
var mk3 = parseInt(mk3);
mark3.push(mk3);
var tot = mk1 + mk2 + mk3;
total.push(tot)
count = count + 1
console.log(mk1 + mk2 + mk3);
console.log(nam);
console.log("the count is " + count)
};
When I run it I get an error:
Uncaught TypeError: undefined is not a function
on Line 12 which is name.push(nam);
I have looked around but I am not sure what I am doing wrong. Help appreciated.

This is an interesting one. It all boils down to an unfortunate choice of variable name. Unfortunately name is a property of the window object. When you refer to name you are actually referring to window.name, not the array called name. If you rename name to something else, it should work just fine.

Related

Using If Else statement to print a count

Im learning JS and Google apps script. Im just working on examples to help learn. Something Im sure is simple that Im stuck on. Is there a way to print out Dell and HP count using the same variable? I know I could add a second variable counter2 and use that but just looking understand preferred methods . I tried to comment out what I have tried. The sheet Im referencing has 100 Dell and 400 HP.
var ss= SpreadsheetApp.getActiveSpreadsheet();
var es = ss.getSheetByName("School1");
var ms = ss.getSheetByName("School2");
var hs = ss.getSheetByName("School3");
var esValues = es.getDataRange().getValues();
var counter = 0;
//var esValues = es.getRange('A:C').getValues();
Logger.log(esValues.length);
for(var i = 0; i < esValues.length; i++){
var data= esValues[i];
var first = data[1];
var last = data[0];
var middle = data[2];
var studentid = data[3];
var device = data[4];
if(device.includes("Dell")){
counter++;
//Logger.log(`Dell count is ${counter}`); //When add here it prints same line 100+ times
} else if(device.includes("HP")){
counter++;
}
}
Logger.log(`Dell count is ${counter}`)//Printing same count 500
Logger.log(`Hp count is ${counter}`)//Printing same count 500
}```
So when logging the total of two different items using one variable isn't the way to do it. In your case both of your conditions will increase counter so while your for loop goes through it will always bump counter so it will hit 500 which is the total number of devices. Try something like this.
var ss= SpreadsheetApp.getActiveSpreadsheet();
var es = ss.getSheetByName("School1");
var ms = ss.getSheetByName("School2");
var hs = ss.getSheetByName("School3");
var esValues = es.getDataRange().getValues();
var counterDell = 0;
var counterHP = 0; // New for just HP
//var esValues = es.getRange('A:C').getValues();
Logger.log(esValues.length);
for(var i = 0; i < esValues.length; i++){
var data= esValues[i];
var first = data[1];
var last = data[0];
var middle = data[2];
var studentid = data[3];
var device = data[4];
if(device.includes("Dell")){
counterDell++;
//Logger.log(`Dell count is ${counter}`); //When add here it prints same line 100+ times
} else if(device.includes("HP")){
counterHP++;
}
}
Logger.log(`Dell count is ${counterDell}`)//Printing same count 500
Logger.log(`Hp count is ${counterHP}`)//Printing same count 500
}
When there are only HP and Dells in device field, it could be resolved.
But if there are more values can be used in device field, there is no solution rather than using two counters.
If only HD and Dells are used, try this one.
var ss= SpreadsheetApp.getActiveSpreadsheet();
var es = ss.getSheetByName("School1");
var ms = ss.getSheetByName("School2");
var hs = ss.getSheetByName("School3");
var esValues = es.getDataRange().getValues();
var counter = 0;
//var esValues = es.getRange('A:C').getValues();
Logger.log(esValues.length);
for(var i = 0; i < esValues.length; i++){
var data= esValues[i];
var first = data[1];
var last = data[0];
var middle = data[2];
var studentid = data[3];
var device = data[4];
if(device.includes("Dell")){
counter++;
}
}
Logger.log(`Dell count is ${counter}`)
Logger.log(`Hp count is ${esValues.length - counter}`)
}```

Google Apps script returning every date minus one day

I assume it has something to do with timezone, but I cannot figure out how to add a day. I would like to only display the month. The issue is at the bottom of the code:
function compull() {
var linkssheet = SpreadsheetApp.openById("1hxkrSKhoUyveyK7dLr-xPpYxhZVvlKJt3S5L6rpMS7w").getSheetByName("Links");
var comsource = SpreadsheetApp.openById("1egqeIX6Lf2As2tsT0U8yhV41fg7as3dOLnwGryU9GVs");
var adjustmentssource = comsource.getSheetByName("Adjustments").getRange("A:I").getValues().filter(function(item){ return item[0] != ""; });
var compullsource = comsource.getSheetByName("Calculator").getRange("A:Q").getValues().filter(function(item){ return item[0] != ""; });
//var length = 4;
var length = 1 + getLastRowSpecial(linkssheet.getRange("E:E").getValues());
var comlength = 1 + getLastRowSpecial(compullsource);
var adjlength = 1 + getLastRowSpecial(adjustmentssource);
for (i=2; i<length; i++) {
var writelocation = SpreadsheetApp.openByUrl(linkssheet.getRange(i,5).getValue());
var compull = writelocation.getSheetByName("Commissions");
var id = linkssheet.getRange(i,1).getDisplayValue();
var id2 = linkssheet.getRange(i,2).getDisplayValue();
var rowlength = comlength;
var columnlength = compullsource[0].length;
dataarray = [];
dataarray.push(compullsource[0].slice());
for (j=1;j<compullsource.length;j++){
if(compullsource[j][1] == id){
dataarray.push(compullsource[j].slice());
}
}
for (k=0;k<dataarray.length;k++){
dataarray[k].splice(1,2);
}
compull.getRange(4,1,dataarray.length,dataarray[0].length).clearContent();
compull.getRange(4,1,dataarray.length,dataarray[0].length).setValues(dataarray);
var rowlength = adjlength;
var columnlength = adjustmentssource[0].length;
dataarray2 = [];
dataarray2.push(adjustmentssource[0].slice());
for (j=1;j<adjustmentssource.length;j++){
if(adjustmentssource[j][1] == id2){
dataarray2.push(adjustmentssource[j].slice());
}
}
for (k=0;k<dataarray2.length;k++){
dataarray2[k].splice(0,2);
}
compull.getRange(4,17,dataarray2.length,dataarray2[0].length).clearContent();
compull.getRange(4,17,dataarray2.length,dataarray2[0].length).setValues(dataarray2);
SpreadsheetApp.flush();
//change date in adjustments in Column Q
var date = compull.getRange("Q5:Q")
var values = date.getValues();
values[0][0] = Utilities.formatDate(date, "GMT-8:00", "MM");
You should know that the spreadsheet settings and the script project have their own timezone, so if you have problems with dates one of the first things that you should check is that each of them is using the correct timezone.
This part of the code is wrong
var date = compull.getRange("Q5:Q")
var values = date.getValues();
values[0][0] = Utilities.formatDate(date, "GMT-8:00", "MM");
The problem is that the first argument of formatDate should be a Date object but date had assigned a Range object.
Resources
Working with Dates and Times

Solving random numbers and random variables from array Javascript

window.onload = start;
var nr1 = Math.floor(Math.random()*50);
var nr2 = Math.floor(Math.random()*50);
var eq1 = nr1 +"+"+nr2;
var eq2 = nr1 + "-"+ nr2;
var eq3 = nr1 +"*"+ nr2;
var eq4 = nr1 +"/"+ nr2;
var arr = [eq1,eq2,eq3,eq4];
var eq = arr[Math.floor(Math.random()*arr.length),Math.floor(Math.random()*arr.length)];
I want to practice something, making a basic Math game. Up there is the code I'm trying to use to generate random numbers and random equations which I want to come out of my html. The reason why I have "" for the operators is because I want the whole equation to come out as a text, I've tried it without the "" marks and I just get the answer straight away.
function start() {
document.getElementById("submit").onclick = submitans;
document.getElementById("question").innerHTML = eq;
}
this is my startup function which generates the equation. Now this works very well in the html if you look at this photo --
HTML. My problem is, I don't know how I'm going to connect the equation to the "if(statement)" from the input box. Because the script reads the commands as text, so it doesn't work even if I write
function submitans() {
var correct = "Correct!";
var wrong = "Wrong";
var inn = parseInt(document.getElementById("answer").value);
for (var i = 0; i < eq.length; i++) {
if(inn === eq[i])
document.getElementById("input").innerHTML = "correct";
}
}
Is there in anyway I can reach the goal I want from this script? I'm sticking with pure javascript, as I am just a beginner, and I really want to learn it. So I'd rather not use jquery.
Aside from this, I'm planning to make my script show the score for every right answer, I thought of having a maximum of 10 right answers for the goal, and the user is allowed to have 5 mistakes.
in the first snippet of code you can add the answer for each equation
var eq1 = nr1 +"+"+nr2;
var eq2 = nr1 + "-"+ nr2;
var eq3 = nr1 +"*"+ nr2;
var eq4 = nr1 +"/"+ nr2;
//answers
var ans1 = nr1 +"+"+nr2;
var ans2 = nr1 + "-"+ nr2;
var ans3 = nr1 +"*"+ nr2;
var ans4 = nr1 +"/"+ nr2;
and then when you get the random equation you get the answer for it too
var arr = [eq1,eq2,eq3,eq4];
var ansArr = [ans1, ans2, ans3, ans4];
var eqNumber = Math.floor(Math.random()*arr.length);
var eq = arr[eqNumber];
var ans = ansArr[eqNumber];
and edit the last snippet like this
function submitans() {
var correct = "Correct!";
var wrong = "Wrong";
var inn = parseInt(document.getElementById("answer").value);
//for (var i = 0; i < eq.length; i++) {//delete
if(inn == ans)
document.getElementById("input").innerHTML = correct;
else
document.getElementById("input").innerHTML = wrong;
//}//delete
}
--------------------------------------------------------------------------------
or instead of all of that you can also only change the last snippet of code like this
function submitans() {
var correct = "Correct!";
var wrong = "Wrong";
var inn = parseInt(document.getElementById("answer").value);
//for (var i = 0; i < eq.length; i++) {//delete
if(inn == eval(eq))
document.getElementById("input").innerHTML = correct;
else
document.getElementById("input").innerHTML = wrong;
//}//delete
}
eval will run the text as javascript and it will return the answer of the equation.
you can also use eval function to get the answer.
var answer = eval(document.getElementById("question").innerHTML) to get the correct answer
I would change the way you manage the equations... Maybe something like that could be useful :
function eq(x, y, op){
// Find the result depending on the operation
var res;
switch (op){
case: '+':
res = x + y;
break;
case: '-':
res = x - y;
break;
case: '*':
res = x * y;
break;
case: '/':
res = x / y;
break;
default:
throw "Error";
}
// Or something like is more compact
var res2 = op == '+' ? x+y : op == '-' ? x-y : op == '*' ? x*y : op == '/' ? x/y : null;
return {
text: x + op + y,
res: res
}
}
// ...
var eq1 = eq(nr1, nr2, '+');
var eq2 = eq(nr1, nr2, '-');
var eq3 = eq(nr1, nr2, '*');
var eq4 = eq(nr1, nr2, '/');
Then you just have to display eq.text in the HTML and check eq.res to compare with the answer... Maybe you can do something nicer but it should work
eval() should work good, try this:
function submitans() {
var correct = "Correct!";
var wrong = "Wrong";
var inn = parseInt(document.getElementById("answer").value);
if(inn === eval(document.getElementById("question").innerHTML))
document.getElementById("input").innerHTML = correct;
else
document.getElementById("input").innerHTML = wrong;
}
there is difference between parseInt and Number
var inn = parseInt(document.getElementById("answer").value);
var inn = Number(document.getElementById("input").value);
========================
eval() you need to be careful with. more so in how javascript will interpret a given string of
var ans1 = eval( 4-3/2*39+3)
adding brackets will make sure you get correct result in how you want evel() to return an answer.
var ans2 = eval( (4-((3/2)*39))+3 );
var ans3 = eval(document.getElementById("equation").value);
will most likely return like ans1, be careful!
to get around issue of above...
var eq1a = nr1 +"+"+nr2;
var eq1b = nr1 + nr2
var eq2a = nr1 + "-"+ nr2;
var eq2b = nr1 - nr2
var eq3a = nr1 +"*"+ nr2;
var eq3b = nr1 * nr2
var eq4a = nr1 +"/"+ nr2;
var eq4b = nr1 / nr2
easy enough above.....
taking next step
var eq1 = "nr1 + nr2"
var eq2 = "nr1 - nr2"
var eq3 = "nr1 * nr2"
var eq4 = "nr1 / nr2"
above is a string that you can do...
var nr1 = Math.floor(Math.random()*50);
var nr2 = Math.floor(Math.random()*50);
var eq1 = "nr1 + nr2"
document.getElementById("equation").innerHTML = eq1;
//and it will show correctly.
var ans = eval(eq1);
// and it will give you the answer
and taking it one more step further....
var eq1 = "((nr1 + nr2) * 4 / 4)"
document.getElementById("equation").innerHTML = eq1.regex();
var ans = eval(eq1);
i forgot what needs to be placed in regex() brackets to remove the ( and ) brackets. so it does not print them out to equation html element.
====================
just be careful with eval() if application is critical application. your application could get hacked quickly.

String to number conversion using JavaScript

This is my html code but the problem is that if I add two strings it always gives the 50 as the addition.
function add()
{
var fname=document.getElementById("fname");
var lname = document.getElementById("lname");
var fstring = fname.toString();
var lstring = lname.toString();
var fl = fstring.length;
var ll = lstring.length;
var f1 = parseInt(fl,10);
var l1 = parseInt(ll,10);
document.getElementById("result").innerHTML = f1 + l1;
}
</script>
Because you are NOT reading the value of the input
var fname=document.getElementById("fname");
var lname = document.getElementById("lname");
var fstring = fname.toString(); //<-- turning object to string
var lstring = lname.toString(); //<-- turning object to string
needs to be
var fname=document.getElementById("fname");
var lname = document.getElementById("lname");
var fstring = fname.value;
var lstring = lname.value;
I think the issue is that you are getting the Element itself, rather than the content of the given element. For example if fname was an input, you'd want to call
var fname=document.getElementById("fname").value;
Current what I'm guessing is happening is that calling toString() on the element itself returns something like [object HTMLInputElement], hence why you always get the same lengths when you do the addition.
If you get the values rather than the elements, your code should then work as expected.
var fstring = fname.toString();
var lstring = lname.toString();
This tries to convert the HTMLElement objects to string, while what you probably want is the value stored in those inputs.
var fstring = fname.value;
var lstring = lname.value;
Also, you don't need to do this:
var fl = fstring.length;
var ll = lstring.length;
var f1 = parseInt(fl,10);
var l1 = parseInt(ll,10);
The length property is a number already.
If you wanted to get the total length of both names, just do
total = fstring.length + lstring.length;
If you wanted to concatenate them, do
fullname = fstring + " " + lstring;
And finally, don't put 1's and small L's in short variable names like that, this can become quite confusing.
Use This
function add(){
var fname=document.getElementById("fname");
var lname = document.getElementById("lname");
var fstring = fname.value.toString();
var lstring = lname.value.toString();
var fullName = fstring +" "+lstring;
alert(fullName )
}
<input type='text' id='fname'/>
<input type='text' id='lname'/>
<input type='button' id='btnOk' onclick='add()' value='OK'/>

JavaScript: Accessing ArrayElement by index of other Array Element? array[array[0]] returns undefined

I am trying to make function which accepts 7 digit code (at minimum) and then loads images/elements of character thus creating a character from code.
I wrote this code:
<script type="text/javascript">
var skins = [];
skins["w"] = "http://example.com/char_elements/base.png";
var eyes = [];
eyes["b"] = "http://example.com/char_elements/eyes/blue.png";
eyes["g"] = "http://example.com/char_elements/eyes/green.png";
eyes["r"] = "http://example.com/char_elements/eyes/red.png";
var hair = [];
hair["b"] = "http://example.com/char_elements/hair/black.png";
hair["w"] = "http://example.com/char_elements/hair/blond.png";
hair["s"] = "http://example.com/char_elements/hair/brown.png";
var mouth = [];
mouth["h"] = "http://example.com/char_elements/mouth/happy.png";
var pants = [];
pants["s"] = "http://example.com/char_elements/pants/shorts.png";
var shoes = [];
shoes["b"] = "http://example.com/char_elements/shoes/black.png";
var torso = [];
torso["s"] = "http://example.com/char_elements/torso/shirt.png"
function LoadChar(code){
var data = code.split(/(?=[a-z])/i);
var skins = [skins[data[0]], eyes[data[1]], hair[data[2]], mouth[data[3]], pants[data[4]], shoes[data[5]], torso[data[6]]];
document.getElementById("out").innerHTML = skins.toString();
}
</script>
<div id="out"></div>
However, when I call LoadChar("wgbhsbs");
It thorws me "Cannot read property 'w' of undefined"
I am still new to Arrays in JS, so I am sure I am making some simple Syntax error or doing something a bit wrong.
So what this does is:
1) Accepts code and splits it into 7 elements (always 7, nothing else) stores it in "data" variable as array.
2) Builds "skins" array by loading: skin[number from code] and same for other elements.
3) For testing purposes I am trying to output skins array, but it stops at step 2.
Is there any explanation to this?
You are recreating the previously defined skins variable.
Use a different name for the variable inside the function, and you'll be fine.
var skins = [];
skins["w"] = "http://example.com/char_elements/base.png";
var eyes = [];
eyes["b"] = "http://example.com/char_elements/eyes/blue.png";
eyes["g"] = "http://example.com/char_elements/eyes/green.png";
eyes["r"] = "http://example.com/char_elements/eyes/red.png";
var hair = [];
hair["b"] = "http://example.com/char_elements/hair/black.png";
hair["w"] = "http://example.com/char_elements/hair/blond.png";
hair["s"] = "http://example.com/char_elements/hair/brown.png";
var mouth = [];
mouth["h"] = "http://example.com/char_elements/mouth/happy.png";
var pants = [];
pants["s"] = "http://example.com/char_elements/pants/shorts.png";
var shoes = [];
shoes["b"] = "http://example.com/char_elements/shoes/black.png";
var torso = [];
torso["s"] = "http://example.com/char_elements/torso/shirt.png"
function LoadChar(code){
var data = code.split(/(?=[a-z])/i);
var other_variable = [skins[data[0]], eyes[data[1]], hair[data[2]], mouth[data[3]], pants[data[4]], shoes[data[5]], torso[data[6]]];
alert(other_variable.toString());
}
LoadChar("wgbhsbs");
You're defining properties of an object. Not an array.
Change
var skins = [];
skins["w"] = "http://example.com/char_elements/base.png";
to
var skins = {};
skins.w = "http://example.com/char_elements/base.png";
Also you're redefining skins inside your LoadChar function as LcSalazar pointed out.
Fiddle

Categories

Resources