In jQuery and node.js environments, suppose you have the following:
var object = new Soda().drink("Coke").drink("Pepsi").drink("7Up");
Now let's say I have a list of N drinks and I don't want to hard code this programatically:
var object = new Soda().drink("D1").drink("D2").drink("Dn")...
What is the programatic approach to this problem if I need this to run sequentially and I can't use:
var object = new Soda();
for (var in j){
object.drink(i);
}
The line new Soda().drink("Coke").drink("Pepsi").drink("7Up") implies that .drink() returns a value that by itself is a valid object to call .drink() again with (either the original object, or some other object that encapsulates the modified state).
If that is the case, you could:
var currentDrinkable = object;
for(var drink in drinks) {
currentDrinkable = currentDrinkable.drink(drink)
}
I am only moderately experienced with JS/jQuery. I am attempting to parse an XML object that I retrieved from IIS, here's some pseudocode that roughly describes my problem:
//accepts an XML Object
function dataFromAjax(object) {
var x; // this is an int used to ID the object
var y;
var z;
var arr = [];
var __data = this;
var xmlObject = object;
function readDataFromXMLObject() {
__data.x = $(xmlObject).find("X").text();
__data.y = $(xmlObject).find("Y").text();
__data.z = $(xmlObject).find("Z").text();
testArr = $(xmlObject).find("TestArrInfo").text().split(",");
if(testArr[0] != null)
__data.arr.push(testArr[0]);
// ...
}
function storeData() {
sessionStorage.setItem(__data.x, JSON.stringify(__data));
}
readDataFromXMLObject();
storeData();
}
In the console it gives me the following error while attempting to parse arr[]:
Uncaught TypeError: Cannot read property 'push' of undefined
When I try manually typing something like sessionStorage.getItem(123) (with and without quotes) it also returns null.
To test the values, I tried both console.log(xmlObject) and console.log(__data.x) for debugging, those worked fine and gave me the XML object and value of x, respectively. Not sure why the array isn't working or why the whole object doesn't save. I'd greatly appreciate any hints.
In this scope you can access to arr directly:
arr.push(testArr[0])
Your this context probably points to window object. window.arr is undefined.
Read about this context in JS: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
Javascript:
This is my example code below. I use prompt() variables to create string values for each loop.
var team = new Object;
team["fwd"] = "forwards";
for (i=1; i <2+1; i++){
var fwdName = prompt("enter player name");
team["fwd"]["p" + i] = fwdName;
}
It is my understanding with the above that in each loop, I get user input to read in a value for each new property (that is created by ["p"+i]) to be set to. The fwdName variable is overwritten with each loop.
I use the following to check that I actually put in values that can be used;
console.log(team.fwd.p1);
console.log(team.fwd.p2);
and I get undefined as output for each statement.
i belive the fwd property of your main object should be an object not a string.
team["fwd"] = {};
I want to create a log function where I can insert variable names like this:
var a = '123',
b = 'abc';
log([a, b]);
And the result should look like this in the console.log
a: 123
b: abc
Get the value of the variable is no problems but how do I get the variable names? The function should be generic so I can't always assume that the scope is window.
so the argument is an array of variables? then no, there is no way to get the original variable name once it is passed that way. in the receiving end, they just look like:
["123","abc"];
and nothing more
you could provide the function the names of the variables and the scope they are in, like:
function log(arr,scope){
for(var i=0;i<arr.length;i++){
console.log(arr[i]+':'scope[arr[i]]);
}
}
however, this runs into the problem if you can give the scope also. there are a lot of issues of what this is in certain areas of code:
for nonstrict functions, this is window
for strict functions, this is undefined
for constructor functions, this is the constructed object
within an object literal, this is the immediate enclosing object
so you can't rely on passing this as a scope. unless you can provide the scope, this is another dead end.
if you pass them as an object, then you can iterate through the object and its "keys" and not the original variable names. however, this is more damage than cure in this case.
I know you want to save some keystrokes. Me too. However, I usually log the variable name and values much like others here have already suggested.
console.log({a:a, b:b});
If you really prefer the format that you already illustrated, then you can do it like this:
function log(o) {
var key;
for (key in o) {
console.log(key + ":", o[key]);
}
}
var a = '1243';
var b = 'qwre';
log({
a:a,
b:b
});
Either way, you'd need to include the variable name in your logging request if you want to see it. Like Gareth said, seeing the variable names from inside the called function is not an option.
Something like this would do what you're looking for:
function log(logDict) {
for (var item in logDict) {
console.log(item + ": " + logDict[item]);
}
}
function logSomeStuff() {
var dict = {};
dict.a = "123";
dict.b = "abc";
log(dict);
}
logSomeStuff();
Don't know if this would really work in JS... but you can use a Object, in which you can store the name and the value:
function MyLogObject(name, value) {
this.name = name;
this.value = value;
}
var log = [];
log.push(new MyLogObject('a', '123'));
log.push(new MyLogObject('b', 'abc'));
for each (var item in log) {
if (item.value != undefined)
alert(item.name + "/" + item.value);
}
Then you can loop thru this Object and you can get the name and the value
You can't access the variable names using an Array. What you could do is use objects or pass the variable names as a String:
var x = 7;
var y = 8;
function logVars(arr){
for(var i = 0; i < arr.length; i++){
alert(arr[i] + " = " + window[arr[i]]);
}
}
logVars(["x","y"]);
I had a somewhat similar problem, but for different reasons.
The best solution I could find was:
MyArray = ["zero","one","two","three","four","five"];
MyArray.name="MyArray";
So if:
x=MyArray.name;
Then:
X=="MyArray"
Like I said, it suited my needs, but not sure HOW this will work for you.
I feel silly that I even needed it, but I did.
test this.
var variableA="valor01"; <br>
var variableB="valor02";
var NamevariableA=eval('("variableA")');<br>
var NamevariableB=eval('("variableB")');<br>
console.log(NamevariableA,NamevariableB);
atte.
Manuel Retamozo Arrué
This is annoying me.
I'm setting an array in beginning of the doc:
var idPartner;
var myar = new Array();
myar[0] = "http://example.com/"+idPartner;
And I'm getting a number over the address, which is the id of partner. Great. But I'm trying to set it without success:
$.address.change(function(event) {
idPartner = 3;
alert(idPartner);
}
Ok. The alert is giving me the right number, but isn't setting it.
What's wrong?
Changing the value of the variable does not re-set the values within the array. That is just something javascript can't do automatically. You would have to re-generate the array for it to have the new id. Could you add the id to the value where you use the array instead of pre-setting the values in the array containing the id?
Edit: For example, you would do:
var myArray = [];
var myId = 0;
myArray[0] = "http://foo.com/id/";
and when you need to use a value from the array, you would do this:
var theVal = myArray[0] + myId;
Try this:
var myvar = ["http://site.com/"];
$.address.change(function(event) {
myvar[1] = 3;
}
then use myvar.join () where you need the full url.
The problem here is that at the line
myar[0] = "http://site.com/"+idPartner;
..you perform a string concatenation, meaning you copy the resulting string into the array at index position 0.
Hence, when later setting idPartnerit won't have any effect on the previously copied string. To avoid such effect you can either always construct the string again when the idPartnervariable updates or you create an object and you evaluate it when you need it like...
var MyObject = function(){
this.idPartner = 0; //default value
};
MyObject.prototype.getUrl = function(){
return "http://site.com/" + this.idPartner;
};
In this way you could use it like
var myGlblUrlObj = new MyObject();
$.address.change(function(event){
myGlblUrlObj.idPartner = ... /setting it here
});
at some later point you can then always get the correct url using
myGlblUrlObj.getUrl();
Now obviously it depends on the complexity of your situation. Maybe the suggested array solution might work as well, although I prefer having it encapsulated somewhere in an object for better reusability.
myar[0] = "http://site.com/" + idPartner;
After this line, myar[0] = "http://site.com/undefined" and it has nothing to do with the variable idPartner no more.
So, after that changing the value of idPartner will affect the value of myar[0].
You need to change the value of myar[0] itself.