accessing elements in a list in javascript html - javascript

I have a list - [getFamilyPkg, getActivePkg, getEligiblePkg, getActivePkgForDeactivation], want to get each element in this list in a javascript function.
How to do it? Thanks in advance.

Assume list is stored in a variable called arr.
for (var i = 0; i < arr.length; i++) {
var elem = arr[i];
// elem is either getFamilyPkg, or getActivePkg, or ...
}

Tommy's answer is actually incorrect. for (var i in arr) loops over all attributes/properties of the arr object prototype, which includes builtin functions like slice(), etc. See jsfiddle example here: http://jsfiddle.net/sEtMw/ (check the console and you will see a bunch of extra properties other than the array elements.
There are a few approaches (once again assuming the array is named arr):
var elem;
for (var i = 0, len = arr.length; i < len; i++) {
elem = arr[i];
// elem is actually one of the array elements here
}
Another option is as follows:
var elem;
while (elem = arr.shift()) {
// elem is one of the array elements
}
Please note that the second approach does not keep the array intact. i.e. at the end of the loop, the array will be empty. But if you are okay with that, the syntax is definitely cleaner. Both approaches are illustrated here: http://jsfiddle.net/z7zKK/. The variable arr is logged at the end to illustrate that it is empty.

Related

JavaScript for loop Index becomes arrayIndex

I have the following JavaScript code fragment
var ip = new Array();
// This array filled with values and passed to function
function calculateTime(ip) {
for (i in ip) {
window.alert(i);
if (!i in myArray) {
myArray[i] = 0;
} else {
myArray[i] += 1;
}
}
}
I expect i to be an index (0, 1, 2 ...) but sometimes window.alert prints "arrayIndex" and because of that my code doesn't work correctly. Can someone explain me the reason? I am new in JavaScript.
for in will loop over all the enumerable properties of an object.
None of the properties that come with an array are enumerable in modern browsers, but any that are added (such as the normal array indexes or any custom named properties) will be.
Somewhere you have some code that is adding an arrayIndex property to your array and it is coming up when you loop over it.
var myArray = [];
myArray[0] = 1;
myArray[1] = 1;
myArray[2] = 1;
myArray.arrayIndex = 1;
for (prop in myArray) {
console.log(prop);
}
If you only want to get numerical indexes, then use a standard for loop.
for (var i = 0 ; i < myArray.length ; i++) {
console.log(i);
}
For arrays, you should use a numeric variable rather than in:
for(var i = 0; i < ip.length; i++)
in is to iterate over the keys of an Object, but even there you have to take much care to filter out inherited properties.
Now, since arrays are objects too in JavaScript, you can assign them object properties:
ip["arrayIndex"] = 'some value';
Then "arrayIndex" will show up in a for...in iteration, whereas in a "normal" for loop, it won't.
Use either
for(var i=0; i<ip.length; i++){
//your code
}
or
ip.forEach(function(val,i){
// your code
});
The for(var x in y) loop works best for Object rather than Array. When you use it on arrays it will loop through all properties including named ones like length not just numerical indices.

Retrieve Index Number of Unique Elements

for (let i = 0; i < arrayItemsLen; i++) {
let uniqueItems = arrayItems.filter(function(item, i, arrayItems) {
return i == arrayItems.indexOf(item);
});
}
This method retrieves unique items in the arrayItems to uniqueItems array. What I want to do is also get the index numbers of each unique element and assign it to another temp array. I can't find a way to achieve that.
E.g.: arrayItems.indexOf(item) gives the index of each unique element, but then, how do I get that index to the tempArray[i], I guess I need a for loop but I really don't know where to put it.
I would use something like
var uniqueIndices = [],
uniqueValues = [];
for(var i=0; i<array.length; ++i) {
if(uniqueValues.indexOf(array[i]) >= 0) continue;
uniqueIndices.push(i);
uniqueValues.push(array[i]);
}
Basically, it iterates array checking if the current value is already in uniqueValues. If it's there, it does nothing and continues to the next iteration. Otherwise, it adds the value to uniqueValues and the key to uniqueIndices.
Using i == array.indexOf(array[i]) like in your question would also work, but it may be slower because array will be bigger than uniqueValues.

Syntax for iterating the comparison of one array to many other systematically named arrays

I have a question about proper syntax in iterative functions. I want to compare one master array to a large set (180+) of other arrays. The large set of arrays to be compared are systematically named (scorespec1, scorespec2, scorespec3...). Each comparison will be made not one-to-one but through an algorithm and then have the results stored in another set of arrays that are also systematically named for later query. I not worried about getting the algorithm right just yet. I'm just not sure of the proper syntax to iterate through my arrays. For instance, this is but one of the syntax structures I have tried but failed to get working:
for (i=01;i=186;i++){
if (scorespec+(i)[04]=unknownspec[16]){
resultarray+(i)[01]=True;
else
resultarray+(i)[01]=False;}}
My main problem here is I don't know how to structure the syntax to include the counter variable in my for-loop in the variable name. I've tried a variety of different syntaxes in addition to what I show above and it just doesn't seem to work right. What syntax should I be using?
There are three parts to the for statement:
for ([initialExpression]; [condition]; [incrementExpression]) {
// The statement (i.e. what will happen on each iteration)
}
To iterate through an array, we need the length of the array and a counter which will move towards that length as we iterate. This is the usual pattern:
var myArray = ['foo', 'bar', 'far']; //...
for (var i = 0; i < myArray.length; i++) {
myArray[i]; // <- this is the current array item
}
It's sensible to cache the array's length like so:
for (var i = 0, l = myArray.length; i < l; i++) {
myArray[i]; // <- this is the current array item
}
Also, FYI, your booleans, true and false, should not be capitalised.
If you had declared your array in global scope you could access them using the window object:
var scorespec1 = "123";
var scorespec2 = "456";
for ( var i = 1; i < 3; i++ ){
alert(window['scorespec' + i]);
}
Or you could use the slow and evil eval:
var scorespec1 = "123";
var scorespec2 = "456";
for ( var i = 1; i < 3; i++ ){
var scorespec;
eval("scorespec = scorespec" + i);
alert(scorespec);
}

chaining methods and selectors using jquery inside of a loop

Is it possible to generate a chain of selectors and methods inside of a loop?
For example, I have an array of elements:
array[0] = '.type1value1, .type1value2, .type1value3';
array[1] = '.type2value1, .type2value2, .type2value3';
array[2] = '.type3value1, .type3value2, .type3value3';
I somehow need to build a chain of methods using the array elements as selectors (by looping or any other possible means!) so that I would end up with the following:-
$('.type1value1, .type1value2, .type1value3').filter('.type2value1, .type2.value2, .type2value3').filter('.type3value1, .type3value2, .type3value3');
If I understand you correctly, you don't even need to do a loop:
var firstSelector = array.shift(); //returns first item in the array and removes it from the original array
var filterSelector = array.join(',');
$(firstSelector).filter(filterSelector);
Why can't you just do something like:
var $test = $(array[0]);
for (var i = 1; i < array.length; i++) {
$test = $test.filter(array[i]);
}
Looking at your example, the value of each array element is exactly the value you want to pass as the selector parameter to .filter()
use the following function to pass it an array of selectors...
function getSet(arrSet){
var elements = $(arrSet[0]);
for (var i = 1; i < arrSet.length; i++) {
elements = $(elements).filter(arrSet[i]);
}
}

Loop through associative array in reverse

I'm using a javascript associative array (arr) and am using this method to loop through it.
for(var i in arr) {
var value = arr[i];
alert(i =") "+ value);
}
The problem is that the order of the items is important to me, and it needs to loop through from last to first, rather than first to last as it currently does.
Is there a way to do this?
Four things:
JavaScript has arrays (integer-indexed [see comments below]) and objects (string-indexed). What you would call an associative array in another language is called an object in JS.
You shouldn't use for in to loop through a JS array.
If you're looping through an object, use: hasOwnProperty.
JavaScript doesn't guarantee the order of keys in an object. If you care about order, use an array instead.
If you're using a normal array, do this:
for (var i = arr.length - 1; i >= 0; i--) {
//do something with arr[i]
}
Warning: this answer is ancient.
If you're here for a quick fix, kindly refer to the much better answer below.
Original answer retained, because reasons. See comments.
Using a temporary array holding the keys in reverse order:
var keys = new Array();
for (var k in arr) {
keys.unshift(k);
}
for (var c = keys.length, n = 0; n < c; n++) {
alert(arr[keys[n]]);
}
For a normal array, I would have done this:
var i = arr.length;
while (i--) {
var value = arr[i];
alert(i =") "+ value);
}
This is faster than a "for" loop.
http://blogs.oracle.com/greimer/entry/best_way_to_code_a
In modern browsers you can now use Object.keys to get your array of properties and step through it in reverse order, allowing you to skip the preliminary key collection loop.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
var keys = Object.keys(subject);
for (var i = keys.length-1; i >= 0; i--) {
var k = keys[i],
v = subject[k];
console.log(k+":",v);
}

Categories

Resources