I would like to know if there is a way of creating a JavaScript object which is randomized. Understand randomized as such: the resulting object has a random set of properties, every of which has a random name. The problem boils down to two:
1) Is it possible to have an object created at runtime, without earlier specifying the amount of properties?
2) Is it possible to randomize names of the object's properties?
I'm looking for an explanation/solution, not only a no/yes answer.
A very crude way to do it, can't think of any use case for it:
function randomObject(){
var ret = {};
var propertyCount= Math.random() * 10;
for (var x = 0; x < propertyCount; x++ ){
ret[Math.random()] = Math.random();
}
return ret;
}
I don't see how it could be useful, but yes, it's possible.
var MAX_PROPERTIES = 50;
var ALLOWED_CHARACTERS_IN_KEY = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
var MAX_KEY_LENGTH = 30;
var object = {};
var propertiesCount = Math.round(Math.random() * MAX_PROPERTIES);
for(var i = 0 ; i < propertiesCount ; i++) {
var keyLength = Math.round(Math.random() * MAX_KEY_LENGTH);
var randKey = "";
for(var j = 0 ; j < keyLength ; j++) {
randKey += ALLOWED_CHARACTERS_IN_KEY[Math.floor(Math.random() * ALLOWED_CHARACTERS_IN_KEY.length)];
}
var randValue = Math.random();
object[randKey] = randValue;
}
Note that some keys could begin with a number, which is not callable with the dot notation.
Example :
{
"NmkQZWeW9_ojadERwK74HXYj43Lw":0.3039316821878978,
"PZiFauEC6H":0.04273172815465165,
"2m7cMrwRPoxpa8LvmpAaJ":0.7010494474513925,
"D":0.4552683870622114,
"HQhIxPxO8tsdocRuGJpnhB7k2PjD":0.18360190519964337,
"rVwM8":0.8681098855694265,
"3Vf5HGYDOmUli3":0.527829742115212,
"fQ4ryGL2cxhJeRd":0.10353706566292953,
"D_DQqODu_":0.1272988336424956,
"8UY0a7":0.17057184875868092,
"8i1uVtPwzl0KRA8iYZ4uKcPKF":0.9554370948377217,
"TTi":0.038665872114993616,
"YofUj9RrK7foQrl":0.5835241172217945,
"sb3SzEB_":0.17136910050721899,
"801FopHCCML4ozrfmjak":0.10999126507324442,
"D8":0.05981337403919851,
"oL8ZZvrAG":0.36816486041399255,
"hfXxJ0sNp42y2HYEDXLBYgZ6mV":0.13977757384990708,
"2xx4AJrQswA5TIcXr":0.8610074761855161,
"68RNcKQmgnh_qTG":0.5234909406332302,
"wJsV8BRo1cT2MtXDuh":0.4497261910215308,
"6yFr4E81bvXK":0.5996413679577888,
"Px2bjBvFSBu":0.017922504534248707,
"yazK1KQbmUhE4Ul1rZX5hf0yulX_JK":0.7105144243046027,
"cXmdnvmP":0.028121925940253756,
"R_fDjw9yBejk3":0.699514797889162,
"z":0.34347612922580006,
"2kTX6Q2tzbCo3":0.678962211994213
}
Related
I need to create dynamically name of variable with a loop .
example:
const1 = test;
const2 = test;
const3 = test;
....
I try this , but that only create 20 same variable name in array
I need a unique name increment by 1 at each loop and return each variable to use after.
function createVariables(){
var accounts = [];
for (var i = 0; i <= 20; ++i) {
accounts[i] = "whatever";
}
return accounts;
}
how can I do this ?
Using Object could be the work around
var accounts = {};
for (var i = 0; i <= 20; ++i) {
accounts["const"+i] = "test";
}
console.log(accounts)
If you need variable (not array), then you can use this code:
for (let i = 0; i <= 20; ++i) {
window[`whatever${i}`] = + i;
}
console.log(whatever0)
console.log(whatever1)
//...
console.log(whatever19)
See in playground: https://jsfiddle.net/denisstukalov/thvc2ew8/4/
What is it that you are trying to achieve? As mentioned in some of the comments, and array would be a better approach.
That said, one solution is to set values on a JavaScript object using string indexer (['']). See example below:
function createVariables(obj){
for (var i = 0; i <= 20; ++i) {
obj[`const${i}`] = "whatever";
}
}
// add it to a new object
const accounts = {};
createVariables(accounts);
console.log(accounts.const1, accounts.const2, accounts.const3);
// avoid adding it to global scope (like window)
createVariables(window);
console.log(const1, const2, const3);
I have an array named globalArrayAllTrades as you see below. I simply like to INVERT the date in a new copy of the array. So I loop through, create a new object and add it to the new array - simple.
Then function does exactly as expected. BUT if the array contains too many objects the code fails with a "FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory".
My laptop has 8 GB of memory...When the NODEJS process crashes it uses about 1.5 GB and about 70% of of totally amount of available memory is used.
I do run the NODEJS app with the parameter: --max_old_space_size=5000 which normally fixes every thing. But not this one and i have tried MANY different ways to code the same function - BUT each and every time - it fails...unless the original array is smaller.
How can I fix this issue?
function invertTrades(){
var original = globalArrayAllTrades.slice();
globalArrayAllTrades.length = 0;
globalListAllTrades.length = 0;
for(var i = 0; i < original.length; i++){
var objS = original[i];
var objE = original[original.length-1-i];
var objInv = new TradePoint(objS.number, objS.matchdate, objE.price, objE.size, objE.issell);
globalArrayAllTrades.push(objInv);
globalListAllTrades[objInv.matchdate] = objInv;
}
}
You can save some memory by making original just contain the properties you need to invert, not the whole TradePoint object. Then you don't need to construct new TradePoint objects, you can modify them in place.
var original = globalArrayAllTrades.map(function(trade) {
return {
trade.price,
trade.size,
trade.issell
};
}).reverse();
globalArrayAllTrades.forEach(function(trade, i) {
trade.price = original[i].price;
trade.size = original[i].size;
trade.issell = original[i].issell;
});
And since all the objects were modified in place, there's no need to update globalListAllTrades.
Another way is to swap the price, size, and issell properties in place between the pairs of elements:
var midpoint = Math.floor(globalArrayAllTrade.length/2);
for (var i = 0; i < midpoint; i++) {
var objS = globalArrayAllTrades[i];
var objE = globalArrayAllTrades[globalArrayAllTrades.length-1-i];
var temp = objS.price;
objS.price = objE.price;
objE.price = temp;
temp = objS.size;
objS.size = objE.size;
objE.size = temp;
temp = objS.issell;
objS.issell = objE.issell;
objE.issell = temp;
}
Have you considered just doing this?
// Copy array and then reverse it
var newArray = [].concat(original).reverse();
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse
I would suggest avoiding to copy that array:
function getInverse(i) {
var objS = globalArrayAllTrades[i];
var objE = globalArrayAllTrades[globalArrayAllTrades.length-1-i];
var objInv = new TradePoint(objS.number, objS.matchdate, objE.price, objE.size, objE.issell);
globalListAllTrades[objInv.matchdate] = objInv;
return objInv;
}
function invertTrades(){
globalListAllTrades.length = 0;
for (var i = 0, l = Math.floor(globalArrayAllTrades.length/2); i < l; i++) {
var j = globalArrayAllTrades.length-1-i;
var a = getInverse(i);
var b = getInverse(j);
globalArrayAllTrades[i] = a;
globalArrayAllTrades[j] = b;
}
}
I'm trying, but unsuccessfully, to get the value of a variable, where the variable name is dynamic
var v_1playerName = document.getElementById("id_1playerName").value;
var v_2playerName = document.getElementById("id_2playerName").value;
for (i = 1; i <=5 i++) {
alert(window["v_"+i+"playerName"]);
}
Is this possible?
A simple thing would be to put the variables in an array and then use the for loop to show them.
var v_1playerName = document.getElementById("id_1playerName").value;
var v_2playerName = document.getElementById("id_2playerName").value;
var nameArray = [v_1playerName,v_2playerName];
for (var i = 0; i < 5; i++) {
alert(nameArray[i]);
}
Accessing variables through window isn't a great idea.
Just store the values in an object and access them using square notation:
var obj = {
v_1playerName: 0,
v_2playerName: 3
}
obj['v_' + 2 + 'playerName']; // 3
If you want to keep named references to things you could use an object.
var playerNames = {};
playerNames['p1'] = document.getElementById("id_1playerName").value;
playerNames['p2'] = document.getElementById("id_2playerName").value;
for (i = 1; i <= 2; i++) {
// dynamically get access to each value
alert.log(playerNames['p' + i])
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Any way to simplify this code?
What is the best way to simplify this for going from 1-19?
var backer1 = document.getElementById("backer-prediction-1").value;
var incentive1 = document.getElementById("incentive-cost-1").value;
var totalIncentive1 = parseInt(backer1,10) * parseInt(incentive1,10);
document.getElementById("incentive-total-1").value = totalIncentive1;
var backer2 = document.getElementById("backer-prediction-2").value;
var incentive2 = document.getElementById("incentive-cost-2").value;
var totalIncentive2 = parseInt(backer2,10) * parseInt(incentive2,10);
document.getElementById("incentive-total-2").value = totalIncentive2;
Last one I posted they gave me a "for" loop.
Still learning this stuff.. Very New, THANKS!!!
Just like the last question, use a for loop:
for(var i = 1; i < 20; i++){
var backer = document.getElementById("backer-prediction-"+i).value;
var incentive = document.getElementById("incentive-cost-"+i).value;
var totalIncentive = parseInt(backer,10) * parseInt(incentive,10);
document.getElementById("incentive-total-"+i).value = totalIncentive;
}
for (var i=1; i<=19; i++) {
var backer = document.getElementById("backer-prediction-" + i).value;
var incentive = document.getElementById("incentive-cost-" + i).value;
var totalIncentive = parseInt(backer,10) * parseInt(incentive,10);
document.getElementById("incentive-total-" + i).value = totalIncentive;
}
This untested code should be enough, unless you need access to the backer and incentive values for each one of the cases after the loop is completed.
Use Array in javascript
var backer=[],
incentive=[],
totalincentive=[];
for(var i=1;i<20;i++){
backer[i] = document.getElementById("backer-prediction-"+i).value;
incentive[i] = document.getElementById("incentive-cost-"+i).value;
totalIncentive[i] = parseInt(backer[i],10) * parseInt(incentive[1],10);
document.getElementById("incentive-total-"+i).value = totalIncentive[i];
}
So you can use them after ending for loop , like
backer[1]....,backer[19]
incentive[1]....,incentive[19]
totalincentive[1]....,totalincentive[19]
If the value of backer and incentive is a number, I'd be tempted to do:
var get = document.getElementById;
var backer, incentive, totalIncentive = 0;
for(var i = 1; i < 20; i++) {
totalIncentive += get("backer-prediction-" + i).value * get("incentive-cost-" + i).value;
}
as the multiplication will implicitly convert numeric strings to numbers. But you really should validate that the content of those elements is a valid number before doing anything, even if using parseInt.
Is the following code valid?
var i;
var objs={};
for (i=0; i <10; i++)
{
objs.i=new FooObject();
}
alert(objs.4.someMethod());
If not, how should it be rewritten to accomplish what I want?
You should edit your code as following:
var i;
var objs = {};
for (i = 0; i < 10; i++) {
objs[i] = new FooObject();
}
alert(objs[4].someMethod());
var i;
var objs = new Array();
for(i = 0; i < 10; i++)
{
objs.push(new FooObject());
}
objs[4].someMethod();
You cannot use numericals for variable names 1. If you want to reference an item by a numerical value, use an array 2. You can then access items by their key in the array. If you want to cycle through, you can use the for...in option 3. It won't matter if your keys are sequential and contiguous:
var x;
var myItems = new Array();
myItems[0] = "Foo";
myItems[9] = "Bar";
myItems[5] = "Fiz";
for (x in myItems) {
alert(myItems[x]);
}
1 http://www.w3schools.com/js/js_variables.asp
2 http://www.w3schools.com/js/js_obj_array.asp
3 http://www.w3schools.com/js/tryit.asp?filename=tryjs_array_for_in
You can't use numbers as variable names, because straight up numbers exist as their own object set in Javascript (i.e, you could think of 4 as already being a global variable that you can't override).