I have a variable with a value, let's say
var myVarMAX = 5;
In HTML I have an element with id="myVar".
I combine the id with the string MAX (creating a string myVarMAX). My question is how can I use this string to access a variable with the same name?
You COULD use eval, but if you have the var in the window scope, this is better
var myVarMAX = 5;
var id="MAX"; // likely not in a var
alert(window["myVar"+id]); // alerts 5
However Don't pollute the global scope!
A better solution is something like what is suggested in the link I posted
var myVars = {
"myVarMin":1,
"myVarMax":5,
"otherVarXX":"fred"
} // notice no comma after the last var
then you have
alert(myVars["myVar"+id]);
Since this post is referred to often, I would like to add a use case.
It is probably often a PHP programmer who gives Javascript/Nodejs a try, who runs into this problem.
// my variables in PHP
$dogs = [...]; //dog values
$cats = [...]; //cat values
$sheep = [...]; //sheep values
Let's say I want to save them each in their own file (dogs.json, cats.json, sheep.json), not all at the same time, without creating functions like savedogs, savecats, savesheep. An example command would be save('dogs')
In PHP it works like this:
function save($animal) {
if(!$animal) return false;
file_put_contents($animal.'.json', json_encode($$animal));
return true;
}
In Nodejs/Javascript it could be done like this
// my variables in NodeJS/Javascript
let dogs = [...]; //dog values
let cats = [...]; //cat values
let sheep = [...]; //sheep values
function save(animal) {
if (!animal) return false;
let animalType = {};
animalType.dogs = dogs;
animalType.cats = cats;
animalType.sheep = sheep;
fs.writeFile(animal + '.json', JSON.stringify(animalType[animal]), function (err){
if (err) return false;
});
return true;
}
Related
Pretty new to Javascript..
I have managed to script this simple code here:
var currentstock = 50;
function stockminus(x){
newcurrent = currentstock - x;
return newcurrent;
};
console.log(stockminus(10));
the output of this must be : 40
How can I store that new output into currentstock as the new value or in other words overwrite that var?
so next time I call that function again, output should be : 30
Becasue the new currentstock is 40 from the previous call
Simple, currentstock = stockminus(10)
The let statement declares a block scope local variable, optionally initializing it to a value.
So, every time you are working in the same scope you can do:
let currentstock = 50;
function stockminus(x) {
return currentstock -= x;
};
console.log(stockminus(10));
console.log(stockminus(10));
var stockDetails = (function(initialValue){
var currentStock = initialValue;
return {
getCurrentStock: function() {
return currentStock;
},
stockminus: function(x) {
//add additional logic to check negative cases
currentStock-= x;
return currentStock;
}
}
})(50);
you can use this type of modular patterns to access data using methods and later extend it as per needs.
access it like
stockDetails.getCurrentStock();
stockDetails.stockminus(10);
I have been working all day trying to pass the value of "returnData.salary" inside the "readData" function to
the object inside the "calculateTax" function which is suppose to take the salary value and calculate state and federal taxes. I am stumped, I can't find anything on the internet which provides a good example for me to work with. The examples are either way to simple or super complex. Any help would be appreciated.
I apologize in advance if I did not submit this question in the correct format. This is my first time asking for help on stackoverflow.
function readForm() {
var returnData = {};
returnData.name = $("#name").val();
returnData.lastName = $("#lastName").val();
returnData.age = $("#age").val();
returnData.gender = $("[name=gender]:checked").val();
returnData.salary = $("#salary").val();
returnData.isManager = $("#isManager").val();
returnData.myTextArea = $("#myTextArea").val();
$("#name2").text(returnData.name);
$("#lastName2").text(returnData.lastName);
$("#age2").text(returnData.age);
$("#gender2").text(returnData.gender);
$("#salary2").text(returnData.salary);
$("#myTextArea2").text(returnData.myTextArea);
if ($(isManager).is(':checked')) {
$("#isManager2").text("Yes");
}
else {
$("#isManager2").text("No");
}
//$("#employeeForm")[0].reset();
} //end of readForm function
function calculateTax() {
console.log("Button Works");
var calculateTax = {
state: function(num) {
num *= 0.09;
return num;
}
, federal: function(num) {
if (num > 10000) {
num *= 0.2;
return num;
}
else {
num * 0.1;
return num;
}
}
, exempt: true
};
}
//Invoke readForm function when the submit button is clicked.
$(document).ready(function () {
$("#btnSubmit").on("click", readForm);
$("#btnCalculate").on("click", calculateTax);
})
</script>
Well, simply put; you can't. Not like this anyway. Or, at least not pass the value to the function directly.
You are using global functions right now, which are not inside a class. If it was inside a class, you could instantiate the class and save it to this (which would be the class' instance). However, I'm assuming classes are a bit over complicated in this case. What you could do, is set variables globally so all functions can use them, like this;
//declare the global variable so it exists for every function
var returnData = {};
function readForm() {
//We do NOT redeclare the "var" again. It's global now.
returnData = {}; //Reset the global variable when this function is called
returnData.name = $("#name").val();
returnData.lastName = $("#lastName").val();
returnData.age = $("#age").val();
returnData.gender = $("[name=gender]:checked").val();
returnData.salary = $("#salary").val();
returnData.isManager = $("#isManager").val();
returnData.myTextArea = $("#myTextArea").val();
//Rest of your function
}
function calculateTax(){
console.log(returnData) //works here
}
Note that you do overwrite global variables, so it's best to reset them on every function call. You might get old data stuck in there, otherwise.
What am I doing wrong, and how can one pass variables to a different function within the same wrapping variable/function.
Example:
function customFunctionWrap(){
this.myVar1 = 0;
this.getCurrentPosition = function(){
if (navigation.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){});
}
},
this.doSomething = function(){ // Works
//Do something, return
this.callWithParams(); //Works
},
//If I remove passing in 'value1',calling it elsewhere works
this.doSomethingWithParams = function(value1){
//Use value1
//Return
},
this.callWithParams = function(){
var value1 = 'xyz'; //Is a variable that changes based on some DOM element values and is a dynamic DOM element
this.doSomethingWithParams(value1); //THROWS TYPEDEF ERROR: this.doSomethingWithParams is not a function
this.getCurrentPosition();
}
};
var local = new customFunctionWrap();
local.doSomething(); //WORKS
I know there is another way to do it and then directly use customFunctionWrap.callWithParams(), but am trying to understand why the former approach is erroring out.
var customFunctionWrap = {
myVar1 : 0,
callWithParams : function(){
}
}
What JS sees:
var customFunctionWrap = (some function)()
returned function is fired, because the last (), so it has to yield/return something, otherwise, like in your code it is "returning" undefined.
So your given code does not work.
The very first fix is to delete last 2 characters from
var customFunctionWrap = (some function)()
to make it return constructor.
Here is my object:
$scope.info = [];
$scope.info = [{"name":"kanye","size":"","folder":"Folder"},{"name":"west","size":"","folder":"Folder"}]
$scope.infoObj = $scope.info.name;
console.log($scope.infoObj);
This return me Undefined. The response should be like this:
[{"name":kanye},{"name":west}]
But how to access the specific properties from a multiple object using angularJS or jquery/js?
This should solve the problem:
$scope.infoObj = $scope.info.map(function(obj){
var x = {};
x['name'] = obj['name'];
return x;
})
for ES6, it can be simplified to:
$scope.infoObj = $scope.info.map(x => ({name:x['name']}))
You can actually do a little bit of refactoring to make your code a little cleaner and more readable. Instead of setting your info value twice, set it once, and add the objects in each line after.
Like this:
$scope.info = [];
$scope.info.push({
"name":"kanye",
"size":"",
"folder":"Folder"
});
$scope.info.push({
"name":"west",
"size":"",
"folder":"Folder"
});
See how clean that is? Now it should be fairly obvious that info is an Array of objects, so doing $scope.info.name won't work. What I would recommend is creating a lookup function that can help grab a list based on the key you provide it.
Something like this:
function lookup(key) {
var result = [];
for (var i = 0; i < $scope.info.length; i++) {
var object = {};
object[key] = $scope.info[i][key];
result.push(object);
}
return result;
}
And then call it like this:
$scope.infoObj = lookup('name');
console.log($scope.infoObj);
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;