object access in a function doesn't work - javascript

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);

Related

Access data from inside a function in the global scope

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));

How do you populate a dynamic variable in AngularJS

The following code gives me the error "Cannot read property PERSON1 of null". If I comment out the line where I try to assign the dynamic variable and uncomment the alert line it pops up alerts with each successive person's name.
function fillInternalRepData() {
var internalRepList = null;
console.log("Querying Table for internal reps");
queryTable(//..blabla..//, "false", function (callbackResp) {
internalRepList = callbackResp;
// alert("TRIGGERED"); //WORKS
// alert(internalRepList.length); //WORKS
angular.forEach(internalRepList, function (rep) {
repName = rep.such;
$scope.internalReps[repName].such = repName;
//alert(repName); //WORKS WHEN LINE ABOVE IS COMMENTED OUT
});
}); //get list of internal reps
I simply want to create/add to the $scope.internalReps object so that I can add stuff to it like $scope.internalReps.PERSON1.Name = "Whatever"; $scope.internalReps.PERSON1.Salary = 100000;
Try adding an empty object for the "internalReps" before your forEach loop. It doesn't look like you've declared the object yet, so it can't dynamically add to a null object.
$scope.internalReps = {};
angular.forEach(internalRepList, function (rep) {
repName = rep.such;
$scope.internalReps[repName] = {};
$scope.internalReps[repName].such = repName;
//alert(repName);
});
var internalReps = {};
angular.forEach(internalRepList, function (rep) {
repName = rep.such;
internalReps[repName] = { such: "" };
internalReps[repName].such = repName;
//alert(internalReps[repName].such);
});
That worked. Thanks for the help!

JavaScript "Prompt" command not working when inserting code

I'm trying to make a project that searches through a block of text, then pushes certain values to the properties of an object, but whenever I put a variable inside of the ingamePrices object at near the bottom of this block of text,
var testPrompt = prompt("Let's figure out how this works");
var rawUSDValue = 0.125;
function item(craftGamePrice, craftMarketPrice, uncraftGamePrice, uncraftMarketPrice, strangeGamePrice, strangeMarketPrice, genuineGamePrice, genuineMarketPrice, vintageGamePrice, vintageMarketPrice, unusualGamePrice, unusualMarketPrice, hauntedGamePrice, hauntedMarketPrice, collectorGamePrice, collectorMarketPrice )
{
this.craftGamePrice = craftGamePrice,
this.craftMarketPrice = craftMarketPrice,
this.uncraftGamePrice = uncraftGamePrice,
this.uncraftMarketPrice = uncraftMarketPrice,
this.strangeGamePrice = strangeGamePrice,
this.strangeMarketPrice = strangeMarketPrice,
this.genuineGamePrice = genuineGamePrice,
this.genuineMarketPrice = genuineMarketPrice,
this.vintageGamePrice = vintageGamePrice,
this.vintageMarketPrice = vintageMarketPrice,
this.unusualGamePrice = unusualGamePrice,
this.unusualMarketPrice = unusualMarketPrice,
this.hauntedGamePrice = hauntedGamePrice,
this.hauntedMarketPrice = hauntedMarketPrice,
this.collectorGamePrice = collectorGamePrice,
this.collectorMarketPrice = collectorMarketPrice
}
var ingamePrices =
{
};
document.write(testPrompt);
so that it's like this
var testPrompt = prompt("Let's figure out how this works");
var rawUSDValue = 0.125;
function item(craftGamePrice, craftMarketPrice, uncraftGamePrice, uncraftMarketPrice, strangeGamePrice, strangeMarketPrice, genuineGamePrice, genuineMarketPrice, vintageGamePrice, vintageMarketPrice, unusualGamePrice, unusualMarketPrice, hauntedGamePrice, hauntedMarketPrice, collectorGamePrice, collectorMarketPrice )
{
this.craftGamePrice = craftGamePrice,
this.craftMarketPrice = craftMarketPrice,
this.uncraftGamePrice = uncraftGamePrice,
this.uncraftMarketPrice = uncraftMarketPrice,
this.strangeGamePrice = strangeGamePrice,
this.strangeMarketPrice = strangeMarketPrice,
this.genuineGamePrice = genuineGamePrice,
this.genuineMarketPrice = genuineMarketPrice,
this.vintageGamePrice = vintageGamePrice,
this.vintageMarketPrice = vintageMarketPrice,
this.unusualGamePrice = unusualGamePrice,
this.unusualMarketPrice = unusualMarketPrice,
this.hauntedGamePrice = hauntedGamePrice,
this.hauntedMarketPrice = hauntedMarketPrice,
this.collectorGamePrice = collectorGamePrice,
this.collectorMarketPrice = collectorMarketPrice
}
var ingamePrices =
{
var testVariable = "sampleString";
};
document.write(testPrompt);
it causes the "prompt" command to stop working. Does anyone know why, or how to fix it?
var ingamePrices =
{
var testVariable = "sampleString";
};
This might be an attempt at one of two things: an object literal, or block syntax which you imagine will contain testVariable. Object literals contain keys and values, they don't contain arbitrary expressions or variable definitions. As an object literal this should be
var ingamePrices =
{
testVariable: "sampleString"
};
Or possibly, if you really did want a testVariable as context for some of the contents of this object, then:
var testVariable = "sampleString",
ingamePrices =
{
blah: [testVariable, "a use of testVariable"]
};
If you were looking for block syntax, and lexical variables, then JavaScript doesn't have them. It only has global and function variables. Which means cases like this become a self-executing function, purely to provide scope:
var ingamePrices = (function() {
var testVariable = "sampleString";
...
return { blah: testVariable };
})()

Js function pass multiple parameters as a single object

I have the following constructor:
var one = new HB.hideShowFacilites.Selectors(".facilities .more-centered", "more-centered", "less-centered", "container-max-height", ".facilities .container-min-height");
Is there a way of passing all of these selectors as a single object?
HB.hideShowFacilites = HB.hideShowFacilites || {};
HB.hideShowFacilites.Selectors = function(sel1, sel2, sel3, sel4, sel5){
this.sel1 = sel1;
this.sel2 = sel2;
this.sel3 = sel3;
this.sel4 = sel4;
this.sel5 = sel5;
};
HB.hideShowFacilites.Selectors.prototype.hideShow = function(){
var $obj1 = $(this.sel1),
$obj2 = this.sel2,
$obj3 = this.sel3;
$obj4 = this.sel4,
$obj5 = $(this.sel5);
$obj1.on('click', function(e){
e.preventDefault();
if($obj1.hasClass($obj2)){
$obj1.removeClass($obj2).addClass($obj3);
$obj5.addClass($obj4);
}
else{
$obj1.removeClass($obj3).addClass($obj2);
$obj5.removeClass($obj4);
}
});
};
$(document).ready(function(){
var one = new HB.hideShowFacilites.Selectors(".facilities .more-centered", "more-centered", "less-centered", "container-max-height", ".facilities .container-min-height");
one.hideShow();
});
Depending on how HB.hideShowFacilites.Selectors is implemented, you could use Function.prototype.apply like this
function foo(args) {
var instance = Object.create(HB.hideShowFacilites.Selectors.prototype);
HB.hideShowFacilites.Selectors.apply(instance, args);
return instance;
}
var one = foo([".facilities .more-centered", "more-centered", "less-centered", "container-max-height", ".facilities .container-min-height"]);
From your edit of how it's defined, this method should work.
It is impossible in pure JS to pass in function with argument list an object with members to be treated as arguments, without modifying function like this:
HB.hideShowFacilites.Selectors = function(selectors){
this.sel1 = selectors.sel1;
this.sel2 = selectors.sel2;
this.sel3 = selectors.sel3;
this.sel4 = selectors.sel4;
this.sel5 = selectors.sel5;
};
function like this expect one argument and treat it as object with sel1, sel2 etc fields.
But in reverse it is possible to use passed argument list as array inside a function like this:
HB.hideShowFacilites.Selectors = function(sel1, sel2, sel3, sel4, sel5){
this.sel1 = arguments[0];
this.sel2 = arguments[1];
this.sel3 = arguments[2];
this.sel4 = arguments[3];
this.sel5 = arguments[4];
};
futhermore, if you do not like modify that function, it is possible to redefine it using something like this
HB.myHideShowFacilites = function(){};
HB.myHideShowFacilites.prototype = HB.hideShowFacilites;
HB.hideShowFacilites.Selectors = function(selectors){
this.sel1 = selectors.sel1;
this.sel2 = selectors.sel2;
this.sel3 = selectors.sel3;
this.sel4 = selectors.sel4;
this.sel5 = selectors.sel5;
};
and then use HB.myHideShowFacilites instead HB.hideShowFacilites

Value of the variable becomes empty when accessed outside the function in node js

I have the following code :
for(var index in workload.elements)
{
var arr = [];
var resourceIdentifiers = {};
var elementinfo = {};
var metadataModified = {};
elementinfo = workload.elements[index];
arr[index] = workload.elements[index].uri;
if(workload.elements[index].parameters.imageUri)
{
arr.push(workload.elements[index].parameters.imageUri);
}
resourceIdentifiers = arr.join(',');
console.log('uri' + resourceIdentifiers);
// connects with mysql and fetch data
mysql.elementlevelpricing(resourceIdentifiers, function(result){
elementlevelpricingSummary = JSON.stringify(result,null,2);
console.log('resultin' + elementlevelpricingSummary);
});
console.log('resultout' + JSON.stringify(elementlevelpricingSummary,null,2))
}
The value of the variable elementlevelpricingSummary becomes empty as {} when accessed outside the called function mysql.elementlevelpricing().
The function passed to mysql.elementlevelpricing is an asynchronous callback, so it is actually running after the console.log line below it. You'll want to do anything you need the data for in the callback itself.

Categories