Adding integers to array on javascript - javascript

I'm developing an application that is supposed to draw some rectangles on a canvas. The idea is draw them by putting each one at the last's side - I mean, start drawing it where the other finishes.
I have created a button that takes the values from an input, that was the easy part. I add this values to an Array, but each time I push the button, the array is empty again. I've heard that I need an 'instance variable', but I'm quite lost right now.
Any help will be welcome.
this is the code
function corta() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var medida1 = document.getElementById('medida2').value;
var medida2 = document.getElementById('medida1').value;
var corte1 = Math.round(medida1);
var corte2 = Math.round(medida2);
var arrayAncho = [];
var arrayLargo = [];
var ancho = 0;
var largo = 0;
arrayLargo.push(medida2);
arrayAncho.push(medida1);
//ancho, largo
document.getElementById('medida2').onclick = function () { this.value = ''; };
document.getElementById('medida1').onclick = function () { this.value = ''; };
//metodo para el ancho
for (var i = 0; i < arrayAncho.length ; i++) {
ancho += arrayAncho[i];
}
if (arrayAncho.length == 1) {
ctx.fillStyle = "#58FA58";
ctx.fillRect(0, largo, corte1, corte2);
} else
if (medida1 > 122 - ancho) {
ctx.fillStyle = "#58FA58";
ctx.fillRect(ancho, largo, corte1, corte2);//ancho, largo
}
medida1 = 0;
medida2 = 0;
}

Every time you run the function you run
var arrayAncho = [];
var arrayLargo = [];
This makes them blank every time. You have to declare them outside of the function and only reference them inside the code block

Related

Removing decimal from string

I'm trying to understand how I can remove a decimal. I have tried Math.trunc() but it never seems to remove. Logger.log(esValues.length) prints 500.0, I tried adding var removeDecimal = Math.trunc(esValues.length) then printing removeDecimal but I still get 500.0
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;
//var esValues = es.getRange('A:C').getValues();
Logger.log(esValues.length); //This prints 500.0, Also tried adding here Logger.log(Math.trunc(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++;
} else if (device.includes("HP")) {
counterHP++;
}
}
Logger.log(`Dell count is ${counterDell}`)
Logger.log(`Hp count is ${counterHP}`)
}
Logger.log(esValues.length.split('.')[0])
breaks the decimal into integer and decimal portions, then we discard the decimal portion.
Actually just not using the logger will elimate the .0. For some stupid reason it has always done that.
function lfunko() {
var ss = SpreadsheetApp.getActive();
var es = ss.getSheetByName("School1");
var vs = es.getDataRange().getValues();
var counterDell = 0;
var counterHP =
for (var i = 0; i < vs.length; i++) {
var device = vs[4];
if (device.includes("Dell")) {
counterDell++;
} else if (device.includes("HP")) {
counterHP++;
}
}
const msg = `HP: ${counterHP} DELL: ${counterDell}`
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(msg),"Counts");
}

JavaScript cannot find method a second time?

I'm attempting to build a poker game. The method in question is very simple, and it works when it runs the first time.
This part isn't perfect convention because I'm just using it to test my methods:
var $ = function (id) { return document.getElementById(id); };
var test = function() {
var deck = new POKER.Deck();
var hand = new POKER.Hand();
for (var i = 0; i < 7; i++){
hand.addCard(deck.dealCard());
}
hand.sortByRank();
for (var j = 0; j < 7; j++){
var img = document.createElement("img");
var card = hand.getCardAtIndex(j); //** <------- WORKS HERE**
img.src = card.getImage();
$("images").appendChild(img);
}
var testHand = new POKER.Hand();
testHand = hand.removePairs();
for (var k = 0; k < testHand.length; k++) {
var img2 = document.createElement("img");
var card2 = testHand.getCardAtIndex(k); // **<------FAILS HERE**
img2.src = card2.getImage();
$("handImg").appendChild(img2);
}
};
window.onload = function() {
test();
};
The first and second loop work, and the hand is displayed and everything. When it gets to the last loop, the debugger tells me "TypeError: testHand.getCardAtIndex is not a function"
I was attempting to test the removePairs method (to test for straights more easily), and when watching the variables in the debugger, testHand clearly gets populated correctly. The method seems to work just fine.
getCardAtIndex:
POKER.Hand.prototype.getCardAtIndex = function(index) {
return this.cards[index];
};
removePairs:
POKER.Hand.prototype.removePairs = function(){
var allCards = this.cards;
var tempCards = [];
var uniqueRanks = [];
var unique;
for(var i = 0; i < allCards.length; i++){
unique = true;
for(var j = 0; j < uniqueRanks.length; j++){
if(allCards[i].getRank() == uniqueRanks[j]){
unique = false;
break;
}
}
if(unique){
uniqueRanks.push(allCards[i].getRank());
tempCards.push(allCards[i]);
}
}
return tempCards;
};
I'm completely perplexed.
var testHand = new POKER.Hand();
testHand = hand.removePairs();
hand.removePairs() returns an Array, not a Hand object.
That's why you don't have access to the getCardAtIndex method.
If cards is a public property you could do:
testHand.cards = hand.removePairs();
Or you can have a setter method:
testHand.setCards(hand.removePairs);

Js function always return the same values

Js beginner here.
I have a function like this:
generateSteps: function() {
var stepsLength = this.data.steps.length;
var dataStepsInit = this.data.steps;
for (var i = 0; i < stepsLength; i++) {
var stepsItem = dataStepsInit[i].ITEM;
var arrayItem = this.animationNodes[stepsItem - 1];
var transition = this.animationParameters[i].transition;
var options = this.animationParameters[i].options;
var speed = this.animationParameters[i].speed;
var delay = this.animationParameters[i].delay;
arrayItem.delay(delay).show(transition, options, speed);
if (dataStepsInit[i].AUDIOID) {
var audioClass = dataStepsInit[i].AUDIOID;
var audioPlayer = this.template.find("audio." + audioClass);
setTimeout(playAudioOnDelay,delay);
};
var playAudioOnDelay = function() {
audioPlayer[0].pause();
audioPlayer[0].currentTime = 0;
audioPlayer[0].play();
};
}
}
What it does is generate data from JSON and display animated elements one by one on delay. Animation part work fine. I can assign required animations and delay to DOM elements and show them in right order.
But what I want to do in the same time is also to play an audio on delay (so I use setTimeout). Everything is almost fine, I play audio in right time (correct delay value) but I always play the same audio (which is last element) because audioPlayer always is the same DOM node.
I think this have something to do with this or I mixed a scope?
Try this:
generateSteps: function() {
var stepsLength = this.data.steps.length;
var dataStepsInit = this.data.steps;
for (var i = 0; i < stepsLength; i++) {
var stepsItem = dataStepsInit[i].ITEM;
var arrayItem = this.animationNodes[stepsItem - 1];
var transition = this.animationParameters[i].transition;
var options = this.animationParameters[i].options;
var speed = this.animationParameters[i].speed;
var delay = this.animationParameters[i].delay;
arrayItem.delay(delay).show(transition, options, speed);
if (dataStepsInit[i].AUDIOID) {
var audioClass = dataStepsInit[i].AUDIOID;
var audioPlayer = this.template.find("audio." + audioClass);
setTimeout(playAudioOnDelay(audioPlayer),delay);
};
}
function playAudioOnDelay(audioPlayer){
return function(){
audioPlayer[0].pause();
audioPlayer[0].currentTime = 0;
audioPlayer[0].play();
}
}
}
Essentially, your problem looks like this: http://jsfiddle.net/po0rLnwo/
The solution is : http://jsfiddle.net/gpfuo1s8/
Check the console in your browser.

Win Pivot App. Need to access some data from a section. Any ideas?

I have a JavaScript Win Pivot Application
Into the Hub I am retrieving some information:
function initPages(options) {
for (var i = 0; i < options.length ; i++) {
var menuItem = options[i];
menuItem.showBanner = (i == 0);
definePages(options);
}
}
and in a .Js file I have the definePages function created:
functions.js:
function definePages(item) {
var action = item[0];
var animation = item[1];
var scyfy = item[2];
var localmovies = item[3];
var clasic = item[4];
var comedy = item[5];
var biography = item[6];
var drama = item[7];
var kids = item[8];
var musical = item[9];
var romantic = item[10];
var suspense = item[11];
var horror = item[12];
var art = item[13];
var personalities = item[14];
var history = item[15];
var society = item[16];
}
Now, in my section 1 I initialize the page by calling another function there:
ready: function (element, options) {
// TODO: Inicializar la página aquí.
options = options || {};
initMovies();
},
function initMovies() {
var element = document.getElementById("movieContainer");
//var movies = ??????????????????????????
//console.log(movies);
//it keeps going
}
I need to be able to retrive, in that var movies, the var action, from the functions.Js or, which is the same, the items[0]...
However, if I call a function in functions.Js, which is defined in section1Page, it won´t work...
I can call functions and pass data from anywhere to functions.Js, but not the other way around...
Any ideas on what should I do? Thanks!!!
I fixed it... I created a global var in function.Js and I get the info from the array in each section later on:
function definePages(item) {
tooSleepyToThink = item;
}
section1Page:
function initMovies() {
var elemento = document.getElementById("movieContainer");
console.log(tooSleepyToThink[0].text);
}

Can't get form total cost

So I have a form with two dropdowns. The first dropdown is the options, and the other is more options. So it's like a mix and match, now I want to calculate the total from the two selected dropdowns. Here's what I got going
var repairCost = new Array();
repairCost["none_repair"] = 0;
repairCost["minor"] = 10;
repairCost["major"] = 20;
repairCost["extreme"] = 30;
var colorCost = new Array();
colorCost["none_color"] = 0;
colorCost["single_portrait"] = 10;
colorCost["group_scene"] = 20;
$("#repair_drop").change(function (event) {
getRepair();
function getRepair(){
var repair = 0;
var form = document.forms["myform"];
var selectedRepair = form.elements["repair_drop"];
repair = repairCost[selectedRepair.value];
return repair
}
});
$("#colorize_drop").change(function (event) {
getColor();
function getColor(){
var color = 0;
var form = document.forms["myform"];
var selectedColor = form.elements["colorize_drop"];
color = colorCost[selectedColor.value];
return color
}
});
var timer1 = null;
clearTimeout(timer1);
timer1 = setTimeout(total, 500)
function total(){
var cost = getRepair() + getColor();
console.log(cost);
}
total();
I end up getting
Uncaught ReferenceError: getRepair is not defined
So for example I'd choose repairCost["minor"] and colorCost["group_scene"], then my result would be $30. I have a timer in there so it automatically calculates the total. Any ideas?
You defined the getRepair function inside another function. Therefore you cannot access it from outside. You have to define it outside the function to be able to access it, like so :
var repairCost = new Array();
repairCost["none_repair"] = 0;
repairCost["minor"] = 10;
repairCost["major"] = 20;
repairCost["extreme"] = 30;
var colorCost = new Array();
colorCost["none_color"] = 0;
colorCost["single_portrait"] = 10;
colorCost["group_scene"] = 20;
function getRepair(){
var repair = 0;
var form = document.forms["myform"];
var selectedRepair = form.elements["repair_drop"];
repair = repairCost[selectedRepair.value];
return repair;
}
function getColor(){
var color = 0;
var form = document.forms["myform"];
var selectedColor = form.elements["colorize_drop"];
color = colorCost[selectedColor.value];
return color;
}
$("#repair_drop").change(function (event) {
getRepair();
});
$("#colorize_drop").change(function (event) {
getColor();
});
var timer1 = null;
clearTimeout(timer1);
timer1 = setTimeout(total, 500)
function total(){
var cost = getRepair() + getColor();
console.log(cost);
}
Why are you declaring functions within your events, and then calling them from there? Either declare them outside the events, or just inline the code - don't do both.

Categories