Loop Variable in Jquery - javascript

I'm using for() to loop a function. In this function, you need to have different variable to specific which container will be update.
When loop, the variable will use string+count integer to have different var name. Example: t=1 > var title1, t=2 > var title2 etc.
Example code:-
for(t = 1; t <= 5; t++) {
var title(t) = function(e){}
}
If I use var var title+t = function(e){}, its not working.
Hope any one can help me on this.

Arrays let you store multiple values and refer to them by an index number. For example:
var title=[];
for (var t=0; t<=4; t++) {
title[t] = //something
}
You can then use an index like title[2] to access items in the array. Arrays in Javascript start counting at 0, so the first item is title[0].

Related

access variable from outside loop

I know that this is fundamental JS, but I'd like a simple explanation. From what I've read, If i declare an empty variable outside of my loop, the variable inside the loop should be accessible globally? Or am I totally wrong?
I would like to access randAd from outside my for loop.
var mobileAds = [
"mobile/bb.jpg",
"mobile/eyeko.jpg",
"mobile/farfetch.jpg",
"mobile/fsb.jpg"
];
var randNum = (Math.floor(Math.random() * mobileAds.length));
var randAd;
var i;
for (i = 0; i < mobileAds.length; ++i) {
randAd = (mobileAds[randNum]);
}
If you want to access every element of randAd outside the for loop try like this var randAd = []; to initialize it as an array. You can easily access it after your for loop but If you use it as a simple variable var randAd;then you'll get the last variable always (it overwrites). So initialize it as an array and push every element inside loop before outputting it.
var mobileAds = [
"mobile/bb.jpg",
"mobile/eyeko.jpg",
"mobile/farfetch.jpg",
"mobile/fsb.jpg"
];
var randNum = (Math.floor(Math.random() * mobileAds.length));
var randAd = []; // see the change here
var i;
for (i = 0; i < mobileAds.length; ++i) {
randAd.push(mobileAds[randNum]); // push every element here
}
console.log(randAd);
You are overthinking. You have done the hard bit in getting a random number between 0 and array's length. So, just get the ad at that index:
var randAd = mobileAds[randNum];
No need to use for loop at all.
If you would like to use randAd it should be initialised as an empty array [] and then push in that array from inside your loop randAd.push(). Like this:
var randAd=[];
var i;
for (i = 0; i < mobileAds.length; ++i) {
randAd.push(mobileAds[randNum]);
}

Google scripts. TypeError: Cannot call method "replace" of undefined

First post please go easy on me.
I have an array that looks something like this [BTC-LTC, BTC-DOGE, BTC-VTC] I am trying to change all the "-" with "_". But am having trouble with using the .replace() method. Here is my code.
var array = [BTC-LTC, BTC-DOGE, BTC-VTC];
var fixedArray = [];
for(var i=0; i <= array.length; i++){
var str = JSON.stringify(array[i]);
var res = str.replace("-","_");
fixedArray.push(res);
};
I tried without using the JSON.stringify but that didn't work either. I have also tried to first create var str = String(); this also did not work. Is it possible that the method .replace() is not available in google scripts?
In your example var array = [BTC-LTC, BTC-DOGE, BTC-VTC];
should be
var array = ["BTC-LTC", "BTC-DOGE", "BTC-VTC"];
However I gather from the comments that this is just a typo in your initial example.
var str = JSON.stringify(array[i]); is redundant. You can just do var str = array[i]; Since the value in the array is already a string, there's no need to turn it into one again - the "stringify" method expects to be given an object or array to work on.
However the main problem is that your for loop goes on one too many iterations. Arrays are zero-based, so you need to stop looping when the index is 1 less than the length of the array, not equal to it. e.g. if array.length is 10 then there are 10 indices, but they start at 0, so the indices are 0,1,2,3,4,5,6,7,8,9. If your loop goes on to equal to array.length, then on the last loop array[10] will be out of bounds, and it's only this last iteration which is giving you the undefined error.
var array = ["BTC-LTC", "BTC-DOGE", "BTC-VTC"];
var fixedArray = [];
for (var i = 0; i < array.length; i++) {
var str = array[i];
var res = str.replace("-","_");
fixedArray.push(res);
}
If I understood correctly, you're trying to edit strings, not variables, so you need quotes in your array, and a g in your replace in case you have multiple things to replace :
var array = ['BTC-LTC', 'BTC-DOGE', 'BTC-VTC'];
var fixedArray = [];
for(var i=0; i <= array.length; i++){
fixedArray.push(array[i].replace(/-/g, '_'));
};
code is working fine if we change as below:
var array = ['BTC-LTC', 'BTC-DOGE', 'BTC-VTC'];

grab the current index of the element from an Array

i have an image array like this
var bigImagesList = document.getElementsByClassName('monique-image');
Now i am trying to check if an image in an array is having current path like tis
for (var i = 0; i < bigImagesList.length; i++) {
if (bigImagesList[i].getAttribute('src') === currentBigImageFilePath) {
// Current Image Big Grab //
currentBigImageToDisplay = bigImagesList[i];
var currentIndex = bigImagesList[i].index;
console.log(currentIndex);
but somehow it says undefined . Please tell me how can i grab the index of the current item in if condition. thanks
When you are looping through the array, already you have the index there, as you are looping through the array of bigImagesList. So you might just need to replace:
var currentIndex = bigImagesList[i].index;
With:
var currentIndex = i;
You don't even need to create a new variable, IMO.

Javascript two dimensional array initialization

Meet with a really weird javascript problem. See my codes below:
function initBadScripts(controlArray) {
var scriptsLine = prompt("Please enter the bad scripts", "debug");
if (scriptsLine != null) {
var pattern = /;/;
var nameList = scriptsLine.split(pattern);
alert(nameList+" "+nameList.length);
for(var counter = 0; counter < nameList.length; counter++){
controlArray[counter][0]=true;
controlArray[counter][1]= new RegExp(nameList[counter],"g");
alert(controlArray[counter][0]);
}
}
alert("wtf!");
}
var controlArray = [[]];
initBadScripts(controlArray);
I defined a function, and call that function. A 2-dimensional array called 'controlArray' is defined with no value. Basically, the function check the user's input and use regular expression to make a 'namelist'. For example, if the user type in
ExampleOne;ExampleTwo
The function will create an array called 'nameList'
nameList=[ExampleOne,ExampleTwo];
Then I want to make a dynamical initialization of the 2-dimensional array called 'controlArray', according to the length of nameList. However this only works fine the nameList'length is 1. If it exceeds one (the user type in 'ExampleOne;ExampleTwo'), the ExampleTwo does not go into the array, and the
alert("wtf");
doesn't run at all. This seems that there is already an error before it. Any comments?
JavaScript doesn't have a true 2-dimensional array. Rather, you're putting a second array inside the first array. Change it to this:
...
for(var counter = 0; counter < nameList.length; counter++){
controlArray[counter] = [true, new RegExp(nameList[counter],"g")];
...
Yes or you declare your variable like that:
var controlArray = [[],[]];
or
var controlArray = new Array(2);
for (var i = 0; i < 2; i++) {
controlArray[i] = new Array(2);
}

How do you write to a span using jQuery?

I'm trying to populate a <span></span> element on the page load with jQuery.
At the moment the value that gets populated into the span is just an integer count.
Here I have named my span userCount:
Users<span id = "userCount"></span>
I am trying to write the value of the span with no success.
$(document).ready(function () {
$.post("Dashboard/UsersGet", {}, function (dataset) {
var obj = jQuery.parseJSON(dataSet);
var table = obj.Table;
var countUsers;
for (var i = 0, len = table.length; i < len; i++) {
var array = table[i];
if (array.Active == 1) {
var name = array.Name;
}
countUsers = i;
}
userCount.innerHTML = countUsers.toString();
});
});
You don't have any usercount variable. Use $(selector) to build a jquery object on which you can call functions like html.
$('#userCount').html(countUsers);
Note also that
you don't need to convert your integer to a string manually.
if you don't break from the loop, countUsers will always be table.length-1.
you have a typo : dataSet instead of dataset. Javascript is case sensitive.
you don't need to parse the result of the request
you don't need to pass empty data : jQuery.post checks the type of the provided parameters
So, this is probably more what you need, supposing you do other things in the loop :
$.post("Dashboard/UsersGet", function (dataset) {
var table = dataset.Table;
var countUsers = table.length; // -1 ?
// for now, the following loop is useless
for (var i=0, i<table.length; i++) { // really no need to optimize away the table.length
var array = table[i];
if (array.Active == 1) { // I hope array isn't an array...
var name = array.Name; // why ? This serves to nothing
}
}
$('#userCount').html(countUsers);
});
Use .html()!
Users<span id = "userCount"></span>
Since you have assigned an id to the span, you can easily populate the span with the help of id and the function .html().
$("#userCount").html(5000);
Or in your case:
$("#userCount").html(countUsers.toString());
Change:
userCount.innerHTML = countUsers.toString();
to:
$("#userCount").html(countUsers.toString());
Instead of:
userCount.innerHTML = countUsers.toString();
use:
$('#userCount').html(countUsers.toString());
You could use
$('#userCount').text(countUsers);
to write data to span
The call back argument should be dataSet rather than dataset?

Categories