This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
javascript - dynamic variables
Dynamic Javascript variable names
I need to create a number of objects on a page and want to name them sequentially. Is there a way to do this in JavaScript?
for (i=0;i<num;i++){
var obj+i = new myObject("param1","param2");
obj+i.someProperty = value;
}
This way I can dynamically create a varying number of objects (dependent on the value "num") and then set their properties appropriately.
I can do this in PHP, is there a way to do it in JavaScript?
This isn't recommended, but does what you're trying to do (if you're running in a browser and not some other js environment).
for (i = 0; i < num; i++) {
window['obj' + i] = new myObject("param1","param2");
window['obj' + i].someProperty = value;
}
obj0.someProperty;
This works because global variables are actually properties of the window object (if you're running in the browser). You can access properties of an object using either dot notation (myObject.prop) or bracket notation (myObject['prop']). By assigning window['obj' + i], you're creating a global variable named 'obj' + i.
The better option is to use an array or parent object to store your objects.
myObjs = {};
for (i = 0; i < num; i++) {
myObjs['obj' + i] = new myObject("param1","param2");
myObjs['obj' + i].someProperty = value;
}
myObjs.obj0.someProperty;
Or use an array like lots of other answers suggest.
That's what arrays are for, to hold a collection of something:
var objs = [];
for (i=0;i<num;i++){
objs[i] = new myObject("param1","param2");
objs[i].someProperty = value;
}
Dynamic variables are almost always a bad idea.
You can create, and you can set/modify properties of that object.
Modified code:
var obj = {}; //
for (i=0;i<num;i++){
obj[i] = new myObject("param1","param2");
obj[i].someProperty = value;
}
I recommend you to use array. as
var obj = []; //
for (i=0;i<num;i++){
obj[i] = new myObject("param1","param2");
obj[i].someProperty = value;
}
Related
This question already has answers here:
Change the value of an array changes original array JavaScript
(3 answers)
Closed 7 years ago.
I'm new to javascript and coding in general, and I could use some help.
I am setting a global variable (generatedNumbers) equal to another variable (numbers) so that I can do some validation on the array. However, when I change the value of numbers, my global variable generatedNumbers gets changed as well. Any help would be appreciated.
var generatedNumbers;
function generateNumbers(numberOfNumbers) {
'use strict';
var i;
generatedNumbers = [];
for (i = 0; i < numberOfNumbers; i = i + 1) {
generatedNumbers.push(generateRandomNumber(9).toString());
}
}
function checkEachValidNumberUsed(userExpression, numbers) {
'use strict';
var i, j;
for (i = 0; i < userExpression.length; i = i + 1) {
for (j = 0; j < numbers.length; j = j + 1) {
if (userExpression[i] === numbers[j]) {
numbers.splice(j, 1);
window.console.log(generatedNumbers);
}
}
}
if (numbers.length !== 0) {
return true;
}
}
function validateExpression(userExpression) {
'use strict';
var numbers, validUserInput;
numbers = generatedNumbers;
window.console.log(generatedNumbers);
if (checkEachValidNumberUsed(userExpression, numbers)) {
document.getElementById("feedbackText").innerHTML = "Each number must be used exactly once.";
} else {
return true;
}
Arrays (and all other non-primitive types) are pass-by-reference, not copied, when you use the assignment operator = or pass them to a function, so any changes made to numbers (or the values of the elements of numbers) will be reflected in generatedNumbers.
For your array here, numbers = generatedNumbers.slice(0); will sufficiently clone the array, but keep in mind that if the contents of the array is not a primitive type (e.g. any object that you use the new keyword to create) will not be cloned: both arrays will reference the same objects.
That's because they both refer to the same object. If you want to make a copy of generatedNumbers (which I think you want to do in validateExpression) use slice.
numbers = generatedNumbers.slice(0);
In Javascript if you have an array
var a = [1,2,3,4];
and assign a to another variable
var b = a;
the two are referring the very same array object... for example after
b.push(99);
a will also see the mutated array.
If you want to make a copy you need to do so explicitly for example with
var b = a.slice();
This question already has answers here:
Serializing to JSON in jQuery [duplicate]
(11 answers)
Closed 8 years ago.
I have some variables xx=0 , yy=7 stored in array called variables , where variables=[xx,yy] , now i stored these values in a json file , and after parsing back the variables array , I want to restore each variable value ( assign value back ) , what is the perfect way to do this , assuming this example is very simple cause i really have large list of variables.
This isn't good but if you want do this automatically I think you don't find better way.
// String with values
var s = '[1,2,3,4,5,6]';
// Expected variables
var a = ('xx,yy,zz,aa,bb,cc,dd,ee').split(',');
// Changing string in String[]
var m = s.match(/\d+/g);
a.forEach(function (v, i) {
// Extract value.
var n = m[i];
// Prevent change empty value.
if(n)
// Set value by evaluation (Be careful, this variable must be in scope!).
// eval is EVIL!
eval('(' + v + '=' + n + ')');
});
If your variables are defined globally, you can try
var variablenames = ["xx", "yy"];
var variables = [xx,yy];
for (var i=0; i<variables.length; i++) {
window[variablenames[i]] = variables[i];
}
may be this:
var variables = {};
variables.xx = 100;
variables.yy = 200;
var jsonObj = JSON.stringify(variables); // converted to Json object
console.log(jsonObj); // outputs: {"xx":100,"yy":200}
var obj1 = JSON.parse(jsonObj);
alert(obj1.xx + " " + obj1.yy); // alerts (100 200);
This question already has answers here:
Dynamic variables names in javascript
(8 answers)
Closed 9 years ago.
I want to make a variable dynamically.
Example-
var a ="pres"+b;
where b is a variable, and then use a as a different variable.
You'll be in a much confortable solution using an object to store values, and the bracket notation :
var store = {};
var theEnd = 'Something';
store['b'+ theEnd] = 10 ;
store['c'+ theEnd] = 20 ;
You can easily iterate in existing keys and values with :
for (var key in store) {
var value = store[key];
console.log(' store has key:' + key + ' having value ' + value);
}
// output :
// store has key bSomething having value 10
// store has key cSomething having value 20
u have to use eval() to do this... but dont be eval! this is not a good style!
Your question is a no logical;
Is normal that a and b are variables|||
You have to use new String("string"); and in your case
var a = new String("pres")+b ;
but you can use simplier var a ="pres"+b;
This question already has answers here:
JavaScript hashmap equivalent
(17 answers)
Closed 6 years ago.
How can you create the JavaScript/JQuery equivalent of this Java code:
Map map = new HashMap(); //Doesn't not have to be a hash map, any key/value map is fine
map.put(myKey1, myObj1);
map.put(myKey2, myObj2); //Repeat n times
function Object get(k) {
return map.get(k);
}
Edit: Out of date answer, ECMAScript 2015 (ES6) standard javascript has a Map implementation, read here for more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
var map = new Object(); // or var map = {};
map[myKey1] = myObj1;
map[myKey2] = myObj2;
function get(k) {
return map[k];
}
//map[myKey1] == get(myKey1);
Just use plain objects:
var map = { key1: "value1", key2: "value2" }
function get(k){
return map[k];
}
function Map() {
this.keys = new Array();
this.data = new Object();
this.put = function (key, value) {
if (this.data[key] == null) {
this.keys.push(key);
}
this.data[key] = value;
};
this.get = function (key) {
return this.data[key];
};
this.remove = function (key) {
this.keys.remove(key);
this.data[key] = null;
};
this.each = function (fn) {
if (typeof fn != 'function') {
return;
}
var len = this.keys.length;
for (var i = 0; i < len; i++) {
var k = this.keys[i];
fn(k, this.data[k], i);
}
};
this.entrys = function () {
var len = this.keys.length;
var entrys = new Array(len);
for (var i = 0; i < len; i++) {
entrys[i] = {
key: this.keys[i],
value: this.data[i]
};
}
return entrys;
};
this.isEmpty = function () {
return this.keys.length == 0;
};
this.size = function () {
return this.keys.length;
};
}
This is an old question, but because the existing answers could be very dangerous, I wanted to leave this answer for future folks who might stumble in here...
The answers based on using an Object as a HashMap are broken and can cause extremely nasty consequences if you use anything other than a String as the key. The problem is that Object properties are coerced to Strings using the .toString method. This can lead to the following nastiness:
function MyObject(name) {
this.name = name;
};
var key1 = new MyObject("one");
var key2 = new MyObject("two");
var map = {};
map[key1] = 1;
map[key2] = 2;
If you were expecting that Object would behave in the same way as a Java Map here, you would be rather miffed to discover that map only contains one entry with the String key [object Object]:
> JSON.stringify(map);
{"[object Object]": 2}
This is clearly not a replacement for Java's HashMap. Bizarrely, given it's age, Javascript does not currently have a general purpose map object. There is hope on the horizon, though: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map although a glance at the Browser Compatability table there will show that this isn't ready to used in general purpose web apps yet.
In the meantime, the best you can do is:
Deliberately use Strings as keys. I.e. use explicit strings as keys rather than relying on the implicit .toString-ing of the keys you use.
Ensure that the objects you are using as keys have a well-defined .toString() method that suits your understanding of uniqueness for these objects.
If you cannot/don't want to change the .toString of the key Objects, when storing and retrieving the entries, convert the objects to a string which represents your understanding of uniqueness. E.g. map[toUniqueString(key1)] = 1
Sometimes, though, that is not possible. If you want to map data based on, for example File objects, there is no reliable way to do this because the attributes that the File object exposes are not enough to ensure its uniqueness. (You may have two File objects that represent different files on disk, but there is no way to distinguish between them in JS in the browser). In these cases, unfortunately, all that you can do is refactor your code to eliminate the need for storing these in a may; perhaps, by using an array instead and referencing them exclusively by index.
var map = {'myKey1':myObj1, 'mykey2':myObj2};
// You don't need any get function, just use
map['mykey1']
If you're not restricted to JQuery, you can use the prototype.js framework. It has a class called Hash: You can even use JQuery & prototype.js together. Just type jQuery.noConflict();
var h = new Hash();
h.set("key", "value");
h.get("key");
h.keys(); // returns an array of keys
h.values(); // returns an array of values
I am trying to remove an element from a Javascript associtive array using the value to find it, but I am having trouble. I have tried splice and JQuery's grep method and neither have worked for me. This is what I currently have.
var array_path = new Array();
function bulk_upload(){
var temp_array = new Object();
for (var i = 1; i<8; i++){
temp_array[i] = $('#path' + i).val();
if(temp_array[i]!='' && temp_array[i]!=null){
array_path['path' + i] = $('#path' + i).val();
}
}
process_txt();
}
function process_txt(){
//alert(array_path.indexOf(full_path)); //returns nothing
var removed_element = array_path.splice(getKey(array_path), 1);
//array_path = $.grep(array_path, function(val) { return val != full_path; });
alert(removed_element);//return nothing, just blank alert box
}
function getKey(data) {
for (var prop in data)
return prop;
}
The way to do this is to use the delete operator.
delete array_path[getKey(array_path)]
Some Background Information
In JavaScript, almost everything descends from Object.prototype. JavaScript, being an open and dynamic language allows you to create/modify properties of objects by simple assignment. This is very similar to what an associative array -- a structure that contains keyed values.
Under the hood an array is just an object that descends from Array.prototype with numeric keys and a special property called length. The length property just returns one greater than the highest numeric property. In essence, an Array is an object with different semantics.
If you're wanting an associative array then Array is not the object you want to descend from. You would want to descend directly from Object. There are two ways to do that, you could either use the new operator or an empty object literal. The syntax for both is below:
var o = new Object();
var o = {};
The second is preferred since it's a little bit more concise.
I wrote a blog post about this a while back, have a look if you want a little bit more info.
There is no such thing in JavaScript as an "associative array" per se. The data structure which corresponds to this concept is simply a JavaScript Object.
Of course, a JavaScript Array (like essentially everything in JavaScript) is an Object, but one with additional capabilities. So you can use an Array as a key-value map, but it's really not the correct structure for that.
To remove a key from an Object, you just do something like this:
var myObj = {};
var myKey = "blah";
myObj[myKey] = 1234; // Adds or updates value for "blah" to 1234.
delete myObj[myKey]; // Removes key-value pair for "blah".
Have you tried delete hash.someKey; ?
You can give your object a remove method, or use apply or call to use another object's remove method, if defined.
function myObj(members){
for(var p in members) this[p]= members[p];
}
myObj.prototype.remove= function(val){
for(var p in this){
if(this[p]=== val) delete this[p];
}
return this;
}
myObj.prototype.toString= function(){
var A= [];;
for(var p in this){
if(this.hasOwnProperty(p)){
A.push(p+':'+this[p])
}
}
return '{'+A.join(', ')+'}';
}
var O= new myObj({a: 1, b: 10, c: 100});
alert(O)
O.remove(10);
alert(O)
I'm not psychic, so I can only guess that you wanted to accomplish something like this:
var paths = [];
function getPaths() {
for(var i = 1; i < 8; ++i) {
var value = $('#path' + i).val();
if(value) paths.push(value);
}
}
function process() {
var firstPath = paths.shift();
// do stuff
}
getPaths();
if(paths.length) process();