calling an object using variable [duplicate] - javascript

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 5 years ago.
I have several javascript sliders on a page and I want to be able to enable or disable each by using a variable.
For example, I have a slider:
var slider1 = new Slider('#sitSlider', {
formatter: function(value) {
return value;} });
and I enable/disable it with this:
slider1.disable();
I would like to be able to do something like this to turn off several switches:
for(x=0;x<20;x++){
var tmpStr = "slider"+x;
tmpStr.disable();
}
I did some searching and tried this without success:
this[tmpStr].disable();
How do I go about using a variable to call an object? Thanks.
Edit: Here's the slider component I'm using: Bootstrap Slider

Create an array:
var sliders = [];
Push your objects onto that array:
sliders.push(new Slider(...));
Then in your loop you can access the array elements:
for(x = 0; x < sliders.length; x++){
sliders[x].disable; // side note: missing parentheses here?
}
Any time you're trying to use an incrementing number as part of a variable name, you're probably looking for an array or collection of some kind.

No. You cannot do that. Variable name shouldn't be given like that.
The easiest you can do create an array and push your sliders. And you can loop the array and access the sliders.
var sldsr =[];
...
sldsr.push(slider1);
...
sldsr.push(slider2);
for(x=0;x<sldsr.length;x++){
sldsr[x].disable();
}

Related

Use a loop to give array items an eventListener with a function with an unique parameter [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 1 year ago.
I'm creating a small project where there are many buttons with the same class calling the same function. I've pushed them into an array using a loop.
Now, depending on the button the user presses, it should call said function, and also pass an unique parameter based on its array index.
So basically, I want to create a loop that gives all the same-classed buttons an eventListener to call the function, but with a different parameter.
This is what i've tried:
let CTAs = []
for(i = 0; i < document.getElementsByClassName("CTAenabled").length; i++) {
CTAs.push(document.getElementsByClassName("CTAenabled")[i])
CTAs[i].addEventListener("click", () => {myFunction(i)})
}
function myFunction(n) {
console.log(n)
}
Using this loop, all buttons are properly pushed into the array, but when pressed, they all pass the same parameter, making the function print the same number.
Any ideas on how to give each button a different parameter according to its index?
Perhaps you could define an array outside of the loop that stores the values needed for the function parameter. These could be accessed with the value of i in your loop. They could also be dynamically generated in a separate for loop if needed.
let CTAs = []
let otherVals = [val1, val2, val3]
for(i = 0; i < document.getElementsByClassName("CTAenabled").length; i++) {
CTAs.push(document.getElementsByClassName("CTAenabled")[i])
CTAs[i].addEventListener("click", () => {myFunction(otherVals[i])})
}
function myFunction(n) {
console.log(n)
}

How to get every value in Json by key in Javascript [duplicate]

This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
Closed 5 years ago.
I am making a rest call to a webservice. In its body it contains a Json file with 18 pairs key, value.
I which to make separate operations on each element so i would like to:
get the different key elements. so i would have an array of the key elements.
With each of those elements, get the corresponding value by dot walking.
Here is what I have:
var obj = JSON.parse(request.body.dataString);
var myKeys = Object.keys(obj)
for (var i = 0; i < myKeys.length; i++){
var iter = myKeys[i];
gs.log(obj.iter);
}
But the gs.log returns undefined.
I have tried to make this:
gs.log(obj.myId);
and it returns the value i want, since myId is one of the elements in keys.
How can i use the elements of my keys array to get the corresponding values?
I have confirmed that hte var myKeys has all the elements of keys and the var obj contains all the json file.
You need to use the [] syntax.
var iter = myKeys[i];
gs.log(obj[iter]);
Plain obj.iter tries to get a property called literally iter. If you want to get a property based on the string value of the variable iter, you need to access the object using obj[iter].

JavaScript/jQuery: array random issue [duplicate]

This question already has answers here:
jQuery - Access elements in array
(3 answers)
Closed 5 years ago.
I'm trying to randomize an array with DOM elements, like this:
var allTargets=$('#target1, #target2, #target3, #target4');
var randomTargets=null;
randomTargets = allTargets[Math.floor(Math.random() * allTargets.length)];
console.log(randomTargets);
In the console I can see the array is shuffled each time I refresh the page. But when I try to trigger a method with the randomTargets variable, the program crashes. Something like this:
randomTargets.hide();
But without the random variable, the program works:
var allTargets=$('#target1, #target2, #target3, #target4');
allTargets.hide();
What am I doing wrong?
Perhaps you meant this which will not shuffle but just hide a random element based on a random number from 0 to length of allTargets
var $allTargets = $('#target1, #target2, #target3, #target4');
var rnd = Math.floor(Math.random() * allTargets.length);
$allTargets.eq(rnd).hide();
Accessing a jQuery object "like an array" gives you a native DOM element which has no hide() method.
From the docs at https://api.jquery.com/get/
Each jQuery object also masquerades as an array, so we can use the
array dereferencing operator to get at the list item instead:
console.log( $( "li" )[ 0 ] );
So in your case $(randomTargets).hide(); will work.

Get a javascript object's property value using a dynamic property key [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 6 years ago.
I am currently working on a project which has a lot of SVG animations. These animations need to be triggered when the user scrolls to the SVG.
I decided to create functions for each Snap.SVG animation and store them in an array of objects using the SVG's ID as the key like so:
//Example Object
var item = {
aboutUsSVG: function(){
//aboutUsSVG animation code to go here
}
}
I have created a Codepen of my code so far here:
http://codepen.io/decodedcreative/pen/mEpZbx
I managed to create the array of objects fine. I have a second function which plays the animation when the SVG is on screen. I am having trouble accessing the animation function stored in the array using a dynamic key.
I can access the function if I know the name of the SVG like so:
var playAnimation = animations.animationsArray[0].ourCompanies;
playAnimation();
But I want to write a solution which can be used for all animations on the site so wish to query the DOM for the SVG ID and then lookup the corresponding animation.
So:
var animationID = $(this).find(".svg-animation svg").attr('id');
var playAnimation = svgAnimations.animationsArray[0].animationID;
playAnimation();
But in the code above animationID is being used literally and not being replaced by the aboutUs function.
I think this is a fairly common JS issue. Can anyone help?
To access a property of an array using a variable you need to use bracket notation:
var animationID = $(this).find(".svg-animation svg").prop('id');
svgAnimations.animationsArray[0][animationID]();
You can use bracket notation to access object property with dynamic variable
check below code
var animationID = $(this).find(".svg-animation svg").attr('id');
var playAnimation = svgAnimations.animationsArray[0][animationID];
playAnimation();

How to sort a bi-dimensional javascript array? [duplicate]

This question already has answers here:
Sort an array based on another array of integers
(7 answers)
Closed 8 years ago.
var global=[];
var value=[50,1,4,29];
var title=["d","b","c","a"];
title.forEach(function(title,i) {
global[title]=value[i];
})
I would like to sort the global array by value but I can't figure out how.
I precise I can't use any library jquery,underscore...
thanks !
the goal is to know what object has the less value.
a,b,c,d have values 50,1,4,29
I can sort values but how to know what's the name associated to this value ?
You're not using global[] correctly as an array in your loop. You can't reference array items with [title], you can either push to the array global.push(value[i]) or use global[i] = value[i]. If you use either of these methods you can just call 'global.sort()' to sort the array which will give you [1, 29, 4, 50]. If you want to use the array as multidimensional, you need to change your loop to something like this:
title.forEach(function(title,i) {
global[i] = {};
global[i][title]=value[i];
})
which will give you [Object { d=50}, Object { b=1}, Object { c=4}, Object { a=29}]
If you want to sort this you could use sort which takes a function in which you can write your custom sorter but I don't think you can use this as all your keys are different. If all your keys were the same, say 'value' ,i.e [Object { value=50}, Object { value=1}, Object { value=4}, Object { value=29}] , you could do:
global.sort(function(a,b) {
return parseInt(a.value, 10) - parseInt(b.value, 10);
});
but this can't be applied to your array since all the keys are different.

Categories

Resources