javascript clean array - javascript

I have four product gallery with the possibility to check the detail of each product from each gallery. Every time the user enter in the detail of any product an array is filled with all the products from that gallery. I should tell this is one single page.
I want to completely delete all the records in the array when the user exits the detail view, because when the user enter again in the detail view the array length increments his size.
I already tried arrayName.length =0; and arrayName.length = [] and it deleted the previous data, but his size continue incrementing like this:
1st time detail view is loaded --> arrayName{valA,valB,valC}
2nd time detail view is loaded --> arrayName{,,,val1,val2,val3}
what it's supposed to be in the 2nd time is: arrayName{val1,val2,val3}
Any idea in how I can solve this issue??
Thanks all
The solution
Thanks all guys. It was my problem.
while($rowDetails = mysql_fetch_array($rsDetails)){
?>
<script language="javascript">
arrayProd[pos] = <?php echo $rowDetails['RefArticleID']; ?>;
pos++;
</script>
...
The array is filled into a while cycle and it increments the pos. At the same time I re-initialize the array I force the pos to be 0 (zero)
arrayProd = [];
pos =0;
Thank you all

This one is really simple, just re-initialize the array:
arrayName = [];

Did you try re-initializing the array by setting it to an empty array?
arrayName = [];

I already tried arrayName.length =0;
That should work, except perhaps for browsers that don't comply with ECMA-262 ed 3 — which shoul be very, very few. In which browser does it fail for you?
and arrayName.length = []
Presumably you meant (otherwise you would see an error):
arrayName = [];
which should work without exception.

Related

Push Values Calendar API

I'm having issues in pushing and returning an array with the events titles. As far as i'm concerned, this should append the title of the events into the titulos array.
for (j=0;j<events.length;j++){
var titulos = []
var events =a.getEventsForDay(testingstartdate, {search: 'OOO'});
var eventstitle = events[j].getTitle();
Logger.log(eventstitle);
titulos.push(eventstitle);
};
The Logger.log in question here is returning correctly one row per title, so no sure why the final array is only pushing 1 single value to it.
Any ideas?
The Logger.log in question here is returning correctly one row per
title, so no sure why the final array is only pushing 1 single value
to it.
This is happening because you define your array in each step of the for loop. Moving the following statement:
var titulos = [];
before the start of the for loop will solve your problem.

Looping over undefined array keys

Problem:
I have a DB containing math exercises, split by difficulty levels and date taken.
i want to generate a diagram of the performance over time.
to achieve this, i loop through the query results, and ++ a counter for the level and day the exercise was taken.
example: level 2 exercise was taken at 01.11.2015.
this.levels[2].daysAgo[1].amountTaken++;
with this, i can build a diagram, where day 0 is always today, and the performance over days is shown.
now levels[] has a predefined amount of levels, so there is no problem with that.
but daysAgo[] is very dynamic (it even changes daily with the same data), so if there was only one exercise taken, it would wander on a daily basis (from daysAgo[0] to daysAgo[1] and so on).
the daysAgo[] between that would be empty (because there are no entries).
but for evaluating the diagram, i need them to have an initialized state with amountTaken: 0, and so on.
problem being: i can't know when the oldest exercise was.
Idea 1:
First gather all entries in a kind of proxy object, where i have a var maxDaysAgo that holds the value for the oldest exercise, then initialize an array daysAgo[maxDaysAgo] that gets filled with 0-entries, before inserting the actual entries.
that seems very clumsy and overly complicated
Idea 2:
Just add the entries this.level[level].daysAgo[daysAgo].amountTaken++;, possibly leaving the daysAgo array with a lot of undefined keys.
Then, after all entries are added, i would loop over the daysAgokeys with
for (var i = 1; i < this.maxLevel; i++) { // for every level
for (var j = 0; j < this.levels[i].daysAgo.length; j++) {
but daysAgo.lengthwill not count undefined fields, will it?
So if i have one single entry at [24], length will still be 1 :/
Question:
How can I find out the highest key in an array and loop until there, when there are undefined keys between?
How can i adress all undefined keys up until the highest (and not any more)?
Or: what would be a different, more elegant way to solve this whole problem altogether?
Thanks :)
array.length returns one higher than the highest numerical index, so can be used to loop though even undefined values
as a test:
var a=[]
a[24]=1
console.log(a.length)
outputs 25 for me (in chrome and firefox).

Get four unique items and add them to an array

I’m 100% certain this code has been working before. Now it strangely doesn’t.
The goal is to create a multiple choice quiz for a flashcard. I create an array to store the card's ids: the first one goes the current card id, then three other random ones. My goal is to make sure they don’t repeat either the first card or themselves.
This is how I do it:
// Array of cards’ ids to use
var randomCardsIds = [];
// Get the active card’s element id, add it to the array
randomCardsIds[0] = this.activeCardId;
// Get the current cards collection
var allCurrentCards = this.carouselEl.items.items;
// Get three random ids of other cards
var i = 0
while (i<3) {
// Get a random card element
var randomCardEl = allCurrentCards[Math.floor(Math.random() * allCurrentCards.length)];
// Get its id
var randomCardElId = randomCardEl.body.down('.card').id;
randomCardElId = randomCardElId.substring(randomCardElId.indexOf('_')+1);
console.log(randomCardElId, randomCardsIds, randomCardsIds.indexOf(randomCardElId));
// Make sure it is not in the array yet, and then add it
if (randomCardsIds.indexOf(randomCardElId) == -1) {
randomCardsIds.push(randomCardElId);
i++;
}
// Otherwise, the loop will have to run again
}
Basically, in a loop, for each item I check whether it already exists in the array or not. If it doesn’t, push it to the array, otherwise, run the loop again. Here is the console logging result:
Well, the first thing: it always shows the final state of the array: as if it is already filled with the results, which is weird. But the most important thing: the script does not recognise a duplicate (e.g. in the first result, 74 is repeated, and in the second to last, 47).
It only returns something different then -1, when it finds a match in the second position (returns 1, obviously). When a match is in a different position in the array, it always returns -1.
What am I doing wrong here?
Are you testing this in IE6? The problem is indexOf doesnot work with IE6.
For alternative you can check Best way to find if an item is in a JavaScript array?
A variation on a shuffling algoruthm seems to be the best bet here.

How to reset a list

It might be a silly question but still i am facing problem with this.
var eformDetailIds = [];
eformDetailIds=$("[name=eform_id]").map(function(){ return $(this).val() }).get();
this is the code that i have written in js function and calling this function on button click.
But the problem is the list eformDetailIds containing the previous values also. could you please how to set this empty list for every function call? Thanks in advance.
Just set the length to zero:
eformDetailIds.length = 0;
Or allocate a new array:
eformDetailIds = [];
Now, that said, according to the code you posted the entire array will definitely be replaced each time that ".map()" call runs. In other words, the previous values will not remain in the array. Perhaps you should post more to explain what it is that makes you think the old values remain.
Don't forget you can always reset the array in this way:
myArray = new Array();
It is pretty easy.

how can i get items in a named array randomly

i want to display questions and below i want to put a textbox for answer. for eg. What is the capital of India.. When the page loads at first time this question appears.. when loads second time another question should appear randomly how to write.. please help me
If you have an array of questions, var questions = ["asdf", "sdfg", ...]; then you can get random ones by:
questions[Math.floor(Math.random() * questions.length)];
Edit: For associative arrays...
Just create a normal array from it:
var questions = [];
for (var i in assocArr) {
if (assocArr.hasOwnProperty(i)) questions.push(assocArr[i]);
}
And then use the above method.

Categories

Resources