Access data from inside a function in the global scope - javascript

I'm still learning JS and I'm currently struggling with this problem. I want to be able to access the data from ordArray in the global scope. How do I do this ? I've tried with returns but struggling to solve it.
const startOrd = function() {
const ordArray = [];
val = document.getElementById("val_ord").value;
ordArray.push(val)
console.log(ordArray)
}

Simply create ordArray outside of the function :)
const ordArray = [];
const startOrd = function () {
val = document.getElementById("val_ord").value;
ordArray.push(val)
console.log(ordArray)
}

Declare/initialize the array outside of the function.
const ordArray = [];
const startOrd = function() {
val = document.getElementById("val_ord").value;
ordArray.push(val)
console.log(ordArray)
}

Your code looks correct, Only thing you want is I've tried with returns but struggling to solve it
Demo :
const startOrd = function() {
const ordArray = [];
const val = document.getElementById("val_ord").value;
ordArray.push(val)
return ordArray;
};
console.log(startOrd());
<input type="text" id="val_ord" value="abcd"/>

Constants are block-scoped, when you create variable in function you dont access to variable out side the function.
please follow the link
I think, This writing code method is more better:
var ordArray = [];
let startOrd = (elem) => elem?.value;
let targetElem = document.getElementById("val_ord");
ordArray.push(startOrd(targetElem));

Related

Error with data for each row function problem with brackets and colons

Hello I am new to the community and I am a novice coder with very little coding experience. I understand some basics and 1st part of the code is working. I am having a problem with the data.foreach(funtion(row) where it is giving a error with brackets and colons
function myFunction() {
var Name = 1;
var Surname = 2;
var AffilliateID = 24;
var emailTemp = HtmlService.createHtmlOutputFromFile("Affiliate email");
}
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Affiliate Responses");
var data = ws.getDataRange("A4:Y" + ws.getLastRow()).getDisplayValues();
data.forEach(function(row) **(**
emailTemp.Name = row[Name]**;**
emailTemp.Surname = row[Surname];
emailTemp.AffilliateID = row[AffiliateID];
))
I have created a var for each line and the tutorial I am following expresses the code as is above. The tutorial may be outdated and some help with an explanation would be appreciated. The bold is the errors.
Thanks
Glenn
For your loop it's something like that
data.forEach(row => {
emailTemp.Name = row[Name]
emailTemp.Surname = row[Surname];
emailTemp.AffilliateID = row[AffiliateID];
})
But to use your
var Name = 1;
var Surname = 2;
var AffilliateID = 24;
var emailTemp = HtmlService.createHtmlOutputFromFile("Affiliate email");
You have to be in the same scope
you need to declare correctly the function that you are passing as a parameter to forEach
const data = [2,5,1,3,4]
data.forEach(function myFunction(item){
console.log(item)
})
you can also use arrow functions:
const data = [2,5,1,3,4]
data.forEach(item => console.log(item))
Welcome to the community. This seems like a simple syntax issue.
You're using ( & ) brackets for function braces, when infact they should be { & } (like your first function).
It's also important that your variables in the right scope. You cannot access the emailTemp variable as it is scoped to your myFunction function. I've moved this into the global scope for you.
Your updated code would look something like this:
function myFunction() {
var Name = 1;
var Surname = 2;
var AffilliateID = 24;
}
var emailTemp = HtmlService.createHtmlOutputFromFile("Affiliate email");
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Affiliate Responses");
var data = ws.getDataRange("A4:Y" + ws.getLastRow()).getDisplayValues();
data.forEach(function(row) {
emailTemp.Name = row[Name];
emailTemp.Surname = row[Surname];
emailTemp.AffilliateID = row[AffiliateID];
});

Scoping Issue with React when calling a function inside a function

I am having some difficulty in getting scope maintained when calling a function within a function when using React, I have created an onChange function, that calls another function called buildBookingQuery
handlePerPageChange = (data) => {
const elementsIndex = this.state.filters.findIndex(element => element.id == 1)
let newArray = [...this.state.filters]
newArray[elementsIndex] = {...newArray[elementsIndex], perPage: parseInt(data.target.value)}
this.setState({
filters: newArray
})
console.log(this.state.filters[0])
console.log(newArray)
let query = this.buildBookingQuery() => This is the problem function
console.log(query)
}
my buildBookingQuery Function
buildBookingQuery (){
let page = 1
let orderby = this.state.filters[0].orderby.split(" ")
let from = this.state.filters[0].fromDate
let to = this.state.filters[0].toDate
let reservedFrom = this.state.filters[0].reservedFromDate
let reservedTo = this.state.filters[0].reservedToDate
console.log("Build Booking Query:", from) => getting undefined
// rest of code removed for sake of brevity
return someValue
}
from researching I have added the bind event to the constructor
this.buildBookingQuery = this.buildBookingQuery.bind(this);
but to no avail.
your help is appreciated
change your buildBookingQuery function to arrow function and also remove binding also.
my issue was myself this line of code:
this.state.filters[0].fromDate
should have been:
this.state.filters[0].startDate
thank for all your help, long day and tired eyes!

I can't nake Reset Button

I need to make reset button which makes Resetting Scores. Can anyone help me?
I tried all my best but I don't know how to make it.
https://github.com/SandroGamrekelashvili/New-folder
const game = () => {
let pScore = 0;
let cScore = 0;
});
const startGame = () => {
const playBtn = document.querySelector(".intro button");
const introScreen = document.querySelector(".intro");
const match = document.querySelector(".match");
There were a few things you needed to get done to make the reset work.
1.) Assign reset button element to a const.
2.) Move your score elements to parent scope.
const game = () => {
let pScore = 0;
let cScore = 0;
const resetBtn = gameContainer.querySelector("button.startOver");
const playerScore = document.querySelector(".player-score p");
const computerScore = document.querySelector(".computer-score p");
// The rest of your code...
2.) Attach event listener to reset button.
const startGame = () => {
playBtn.addEventListener("click", () => {
introScreen.classList.add("fadeOut");
match.classList.add("fadeIn");
});
resetBtn.addEventListener("click", () => {
playerScore.innerText = '0';
computerScore.innerText = '0';
pScore = cScore = 0;
});
};
Here is a JSFiddle with a working example.
I think what you need to solve your problem is very well explained in this other questions here.
The idea is that instead of declaring your variable inside your main function, you would create a variable that refer to your functions related to your score outside of it that can then be called when you need it. To avoid global conflict, you would have that function return an object with functions inside for getters and setters. In your case, I would do something like this:
const scoreModule = () => {
let pScore = 0;
let cScore = 0;
return {
getPScore: () => pScore,
getCScore: () => cScore,
setPScore: value => pScore = value,
setCScore: value => cScore = value,
}
}
Because you defined the scoreModule as a global object, you can then use it wherever you want. And, because you returned only getters and setters (not the actual value, but rather a mean to get or change them) your object is protected and you avoid the bad practice of globally available variables. Then in any of your other functions, when you want to use them either to get or set them, you simply:
const game = () => {
// To get a score
const currentPScore = scoreModule().getPScore()
// To set a score
scoreModule().setPScore(newScore)
});

object access in a function doesn't work

This is the code:
(function(Info, undefined) {
var createInfoTableForFeature = function (obj) {
var data2form = {};
data2form.name = obj.name;
data2form.state = obj.state;
data2form.stateid=obj.stateId;
data2form.city = obj.city;
data2form.cityId=obj.cityId;
data2form.sector = obj.sector;
data2form.sectorId=obj.sectorId;
data2form.municipality = obj.municipality;
data2form.municipalityId=obj.municipalityId;
data2form.parish = obj.parish;
data2form.parishId = obj.parishId;
data2form.postcode = obj.postcode;
}
Info.copy2form = function(data){
console.log(data);
}
})(window.Info = window.Info || {});
When I call Info.copy2form(data2form), data2form is undefined
You want data2form to be global, then you'll have to remove de var keyword before the declaration of the variable data2form to make it global.
If you want to make it accesible from everywhere but within Info container, then you can declare it like this:
Info.data2form = {};
and then call your function like this:
Info.copy2form(Info.data2form)
Your post doesn't seem JSON related so far, oh well.
Your data2form doesn't exist outside the function. You should assign it to window.data2form or define the var data2form outside the function.
This won't work because data2form is a local variable inside of the anonymous function (createInfoTableForFeature).
This is one of 1000 solutions:
function createInfoTableForFeature(obj) {
var data2form = {};
data2form.name = obj.name;
data2form.state = obj.state;
data2form.stateid=obj.stateId;
data2form.city = obj.city;
data2form.cityId=obj.cityId;
data2form.sector = obj.sector;
data2form.sectorId=obj.sectorId;
data2form.municipality = obj.municipality;
data2form.municipalityId=obj.municipalityId;
data2form.parish = obj.parish;
data2form.parishId = obj.parishId;
data2form.postcode = obj.postcode;
return data2form;
}
var data2form = createInfoTableForFeature(obj);
Info.copy2form(data2form);

Javascript array is undefined... and I'm not sure why

I'm trying to translate a PHP class into JavaScript. The only thing I'm having trouble with is getting an item out of an array variable. I've created a simple jsfiddle here. I cannot figure out why it won't work.
(EDIT: I updated this code to better reflect what I'm doing. Sorry for the previous mistake.)
function tattooEightBall() {
this.subjects = ['a bear', 'a tiger', 'a sailor'];
this.prediction = make_prediction();
var that = this;
function array_random_pick(somearray) {
//return array[array_rand(array)];
var length = somearray.length;
var random = somearray[Math.floor(Math.random()*somearray.length)];
return random;
}
function make_prediction() {
var prediction = array_random_pick(this.subjects);
return prediction;
}
}
var test = tattooEightBall();
document.write(test.prediction);
​
Works fine here, you are simple not calling
classname();
After you define the function.
Update
When you make a call to *make_prediction* , this will not be in scope. You are right on the money creating a that variable, use it on *make_prediction* :
var that = this;
this.prediction = make_prediction();
function make_prediction() {
var prediction = ''; //initialize it
prediction = prediction + array_random_pick(that.subjects);
return prediction;
}
You can see a working version here: http://jsfiddle.net/zKcpC/
This is actually pretty complex and I believe someone with more experience in Javascript may be able to clarify the situation.
Edit2: Douglas Crockfords explains it with these words:
By convention, we make a private that variable. This is used to make
the object available to the private methods. This is a workaround for
an error in the ECMAScript Language Specification which causes this to
be set incorrectly for inner functions.
To see the complete article head to: http://javascript.crockford.com/private.html
You never call classname. Seems to be working fine.
Works for me:
(function classname() {
this.list = [];
this.list[0] = "tiger";
this.list[1] = "lion";
this.list[2] = "bear";
function pickone(somearray) {
var length = somearray.length;
var random = somearray[Math.floor(Math.random()*length)];
return random;
}
var random_item = pickone(this.list);
document.write(random_item);
}());
Were you actually calling the classname function? Note I wrapped your code block in:
([your_code]());
I'm not sure what you're trying to accomplish exactly with the class structure you were using so I made some guesses, but this code works by creating a classname object that has instance data and a pickone method:
function classname() {
this.list = [];
this.list[0] = "tiger";
this.list[1] = "lion";
this.list[2] = "bear";
this.pickone = function() {
var length = this.list.length;
var random = this.list[Math.floor(Math.random()*length)];
return random;
}
}
var cls = new classname();
var random = cls.pickone();
You can play with it interactively here: http://jsfiddle.net/jfriend00/ReL2h/.
It's working fine for me: http://jsfiddle.net/YznSE/6/ You just didn't call classname(). If you don't call it, nothing will happen ;)
Make it into a self-executing function like this:
(function classname() {
this.list = [];
this.list[0] = "tiger";
this.list[1] = "lion";
this.list[2] = "bear";
function pickone(somearray) {
var length = somearray.length; //<---WHY ISN'T THIS DEFINED??
var random = somearray[Math.floor(Math.random() * length)];
return random;
}
var random_item = pickone(this.list);
document.write(random_item);
})();
var test = tattooEightBall();
document.write(test.prediction);
Should be:
var test = new tattooEightBall(); //forgot new keyword to create object
document.write(test.prediction()); // forgot parens to fire method
and:
this.prediction = make_prediction();
Should be:
this.prediction = make_prediction;

Categories