I have a bunch of jQuery objects with a init method, so right now I have something like this
$.myobject1.init(somevar);
$.myobject2.init(somevar);
$.myobject3.init(somevar);
$.myobject4.init(somevar);
$.myobject5.init(somevar); // somevar is the same var in all the calls
but I'm looking for a way to simply this code, something like this
var objectName = "myobject1"; // or any other object name
$. objectName .init(somevar);
thanks for the help! :-)
Since they are already jQuery objects you don't need $. and you can use .add() like this :
var object = myobject1.add(myobject2).add(myobject3).add(myobject4).add(myobject5);
object.init(somvar)
Just use
$[objectName].init(somevar);
in javascript, all objects are maps. it's really weird, but it means you can do this trick:
var p = "mypropertyname";
var obj = {};
obj[p] = somevalue;
then, if you do:
console.log(obj.mypropertyname)
you'll get:
> somevalue
If you mean you want to loop through the names of your objects, then you should know that you can't combine strings with dot notation:
var someObj = {
subObj: {
a: 5
}
};
someObj.subObj.a === 5; // true
someObj."subObj".a === 5; // throws error
But you can use strings with square bracket notation:
someObj["subObj"].a === 5; // true
var propName = "subObj";
someObj[propName].a === 5; // true
So you can use that to loop through your object names with a for loop, or you can use a jQuery method as suggested in other answers.
Related
vm.contributorAmountPerYear[index-1] gets me an object, and I want its key to be the year argument of the function.
function getAgriAmount(year,amount,index) {
if (typeof amount !== "number" ) {
amount = parseInt(amount ||0);
};
var argiYearlyLocalCost = vm.argiterraYearlyLocalCost;
console.log(vm.contributorAmountPerYear[index-1].year);
}
vm.contributorAmountPerYear[index-1][year]
For any javascript object, you should keep in mind that if you use . dot notation, you cannot access the properties for keys that come from a variable and are determined at runtime. Use square bracket notation [] for such a case. This should work:
vm.contributorAmountPerYear[index-1][year];
Dot notation should be used when you already know the key:
var cuteJavaScriptObject = {
animal : 'cat'
}
var myVar = 'animal';
console.log(cuteJavaScriptObject.animal); // OK
console.log(cuteJavaScriptObject.myVar); // Wrong !!
console.log(cuteJavaScriptObject[myVar]); // Now OK
Say I already have many objects, like obj1, obj2, .....obj30.....
Now I am trying to write a function like this:
function blar(N){
do something to objN
}
blar('4');
So far it seems that the only way to do it is
function blar(thisObj){
do something to thisObj
}
blar(obj4);
I wonder what is the right way to pass the N such that the function can use that N value to process objN.
Hope I make myself clear.
PS: I even try something like blar(obj+N) but apparently it's wrong too, as the system tries to find obj, which doesn't exist.
Use square bracket notation.
window['obj' + N];
This depends on them dangling off the window object and not being nicely scoped though.
… but if you have a bunch of objects, which are identified by being the same except for a number, then you should probably be storing them in an array in the first place. Then you would just:
myArray[N];
Use eval:
function blar(N) {
var obj = eval("obj"+N);
}
Or, if you can put those objects into an object, you can use []
function blar(N) {
var obj = tracker["obj" + N];
}
It's pretty simple:
function blar(objectNo) {
var obj = eval('obj' + objectNo);
alert(obj);
}
To give you some keywords for talking with others about this: what you want to do is to access an object by its name, in the current scope.
But note that the following doesn't work:
function main() {
var a = 1, b = 2, c = 3;
blar('a'); // doesn't work
doSomething(eval('a')); // works
}
This is because the variable a is only visible in the main function, but not in blar. That is, the eval must be called in a scope where the variable is visible.
I'm trying to create an array that maps strings to variables. It seems that the array stores the current value of the variable instead of storing a reference to the variable.
var name = "foo";
var array = [];
array["reference"] = name;
name = "bar";
// Still returns "foo" when I'd like it to return "bar."
array["reference"];
Is there a way to make the array refer to the variable?
Put an object into the array instead:
var name = {};
name.title = "foo";
var array = [];
array["reference"] = name;
name.title = "bar";
// now returns "bar"
array["reference"].title;
You can't.
JavaScript always pass by value. And everything is an object; var stores the pointer, hence it's pass by pointer's value.
If your name = "bar" is supposed to be inside a function, you'll need to pass in the whole array instead. The function will then need to change it using array["reference"] = "bar".
Btw, [] is an array literal. {} is an object literal.
That array["reference"] works because an Array is also an object, but array is meant to be accessed by 0-based index. You probably want to use {} instead.
And foo["bar"] is equivalent to foo.bar. The longer syntax is more useful if the key can be dynamic, e.g., foo[bar], not at all the same with foo.bar (or if you want to use a minimizer like Google's Closure Compiler).
Try pushing an object to the array instead and altering values within it.
var ar = [];
var obj = {value: 10};
ar[ar.length] = obj;
obj.value = 12;
alert(ar[0].value);
My solution to saving a reference is to pass a function instead:
If the variable you want to reference is called myTarget, then use:
myRef = function (newVal) {
if (newVal != undefined) myTarget = newVal;
return myTarget;
}
To read the value, use myRef();. To set the value, use myRef(<the value you want to set>);.
Helpfully, you can also assign this to an array element as well:
var myArray = [myRef];
Then use myArray[0]() to read and myArray[0](<new value>) to write.
Disclaimer: I've only tested this with a numerical target as that is my use case.
My solution to saving a reference is to pass a function instead:
If the variable you want to reference is called 'myTarget', then use:
myRef = function (newVal) {
if (newVal != undefined)
myTarget = newVal;
return myTarget;
}
To read the value, use myRef();. To set the value, use myRef(value_to_set);.
Helpfully, you can also assign this to an array element as well:
var myArray = [myRef];
Then use myArray0 to read and myArray[0](value_to_set) to write.
Disclaimer: I've only tested this with a numerical target as that is my use case.
I have this on a javascript var: (it's a http returned data, and I don't know if it's an array or string - (how can we see that?) - Update: using typeof returned "string", so it's a string.
[{"nomeDominio":"gggg.fa"},{"nomeDominio":"rarar.fa"}]
How can we pass/transform that, into something like this:
["gggg.fa","rarar.fa"]
?
Thanks a lot,
MEM
You can figure out if is a string or an already parsed object by checking the type of your variable, e.g.:
ajax('url', function (response) {
alert(typeof response);
});
You will now figure out if it's a "string" or an Array "object".
If it's a string, you can use the JSON.parse method as #alcuadrado suggest, otherwise you can simply use the array.
Several answers suggest the use of the for-in statement to iterate over the array elements, I would discourage you to use it for that.
The for-in statement should be used to enumerate over object properties, to iterate over Arrays or Array-like objects, use a sequential loop as #Ken Redler suggests.
You should really avoid for-in for this purpose because:
The order of enumeration is not guaranteed, properties may not be visited in the numeric order.
Enumerates also inherited properties.
You can also use the Array.prototype.map method to meet your requirements:
var response = [{"nomeDominio":"gggg.fa"},{"nomeDominio":"rarar.fa"}];
var array = response.map(function (item) { return item.nomeDominio; });
// ["gggg.fa", "rarar.fa"]
This question is strongly related with this one.
I would suggest reading my answer there, as it would really help; and with a little variation, it would just work:
var responseString = '[{"nomeDominio":"gggg.fa"},{"nomeDominio":"rarar.fa"}]',
responseObject = JSON.parse(responseString),
nombresDeDominio = [];
for(var i in responseObject) {
nombresDeDominio.push(responseObject[i].nomeDominio)
}
Suerte!
Assuming your data always looks like that, you can do something like this:
var foo = [{"nomeDominio":"gggg.fa"},{"nomeDominio":"rarar.fa"}];
var newarr = [];
for ( var i=0,j=foo.length;i<j;i++ ) {
newarr.push( foo[i]['nomeDominio'] );
}
Here's a working fiddle.
function transform(array, f) {
var ret = [];
$.each(array, function(index) {
var v = f.call(this, index);
if(v) {
ret.push(v);
}
});
return ret;
}
var result = transform(
[{"nomeDominio":"gggg.fa"},{"nomeDominio":"rarar.fa"}],
function() { return this.nomeDominio; }
);
alert(result.toString());
it's a http returned data, and I don't
know if it's an array or string
It's JSON, and you can use it directly in JavaScript.
If you transform it into your array, you will lose the association key / value ; are you sure it's what you want ?
Okay, firstly to get the type of a "thing", use the "typeof" operator (note that the type of an array is an object, not 'array'!):
var a = "string";
var b = 1;
var c = new Array();
alert(typeof(a)); // string
alert(typeof(b)); // number
alert(typeof(c)); // object
To get at the values in the associative array (assuming it is one), you can just loop through it, like so:
var d = [{"nomeDominio":"gggg.fa"},{"nomeDominio":"rarar.fa"}];
d["bob"] = "alice";
d["gary"] = "stephen";
for(var key in d) {
alert(d[key]);
}
Say I have the following JS:
var foo_index = 123;
var bar_index = 456;
And the following HTML:
<div id="foo"></div>
<div id="bar"></div>
Then I'd like to say this:
thisIndex = this.id + '_index'
And I'd like thisIndex to be a number. How do I turn the string, which is exactly the variable name, into a variable?
You should put the variables in an object, like this:
var indices = {
foo: 123,
bar: 456
};
var thisIndex = indices[this.id];
This code uses JSON syntax an object literal to define an object with two properties and uses [] to access a property by name.
You can also write
var indices = new Object;
indices.foo = 123;
indices["bar"] = 456;
You can. If foo_index and bar_index are global variables, you can simply do:
var thisIndex = window[this.id + '_index'];
you can try using the eval function:
http://www.w3schools.com/jsref/jsref_eval.asp
it does exactly what you need.
window["myvar"] = 'hello';
alert(myvar);
To answer your question, you can use the eval function to evaluate a string:
thisIndex = eval(this.id + '_index');
However, using the eval function is generally a sign of badly constructed code. I think that you should use an associative array instead:
var numbers = { foo: 123, bar: 456 };
thisIndex = numbers[this.id];
I am not sure what do you want to achieve, but maybe this approach could be better (it depends on some factors like version of HTML you use as #Andy E points in comment below):
<div id="foo" index="123"></div>
<div id="bar" index="456"></div>
<script>
var fooIndex = document.getElementById("foo").getAttribute("index");
</script>
Here value of index is kept together with corresponding HTML element.
I think you want something like this:
// put your properties in an object of some kind
var dictionary =
{
foo_index: 123,
bar_index: 456
};
// you can set further properties with property syntax
dictionary.again_index = 789;
// or dictionary syntax - same result
dictionary['another_index'] = 012;
// then function to get the number value from the index name becomes
var thisIndex = Number(dictionary[this.id + '_index']);