Mysterious 'function' being attached to array - javascript

I have the following code:
// button sets
var sets = ['.diamond-colour','.diamond-cut','.diamond-clarity','.diamond-certificate'];
// for each set
for (set in sets){
console.log('Set: '+set);
console.log(sets[set]);
}
The console log shows:
Set: 0
.diamond-colour
Set: 1
.diamond-cut
Set: 2
.diamond-clarity
Set: 3
.diamond-certificate
Set: findIndex
function (value){
var ctr = "";
for (var i=0; i < this.length; i++) {
if (this[i] == value) {
return i;
}
}
return ctr;
}
It appears to be a new array element with the key of findIndex and a value being that function.
Would anyone have any idea what this is and why it's appearing?

You should use a traditional for loop to iterate over an array, otherwise you may pick up properties (in this case a new function) added by yours or 3rd-party code.
for(var i = 0; i < sets.length; i++) {
As others have mentioned, caching the length provides optimal performance:
for(var i = 0, len=sets.length; i < len; i++) {

This is because the in operator with for loops in Javascript loops over the properties of the object, not just the objects in the "Array". I say "Array" because Javascript arrays are really just objects with numeric properties created for each entry in the array (and some additional methods and properties like .length).
As Dennis mentioned, you'll want to use a traditional for loop to loop over just the objects in the array.
Also note that an easy optimisation for such for loops is to initialise the length value once at the start of the loop, rather than evaluating array.length each time:
for (var i = 0, len = sets.length; i < len; i++) {
// ...
}

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.

Using 2 arrays of objects, iterate over them using something similar to IndexOf (or other option)

I have an array of objects, i was trying to iterate over. The array is pretty simple in format.
{a:5, b:"key", c:19}
i was trying to compare an array with a subset, say: [{a:5},...]
for (var i = 0; i < subset.length; i++) {
var searchTerm = subset[i].a;
var index = objs.indexOf(searchTerm, function (el) {
return el.a;
});
if (index > -1) {
objs[index].Found = true;
}
}
So that way ultimately objs, could have a new key in it, 'Found'
This way, it will set the main array objs item.Found = true, if it existed in subset.
There are 2 issues though. Accounting for multiple instances of the same item, and the fact that this current implementation doesnt seem to work.
This is a slight expansion of (indexOf method in an object array? )but with an array of search terms.
ideally, i dont want to change the arrays at all, so im trying not to slice, etc.
In a lot of the defintions, indexOf is defined as:
function indexOf (key, start);
instead of the ideas i am trying to work with.
Edit
Here is some code that i have to get this working, but i was thinking there is a more effecient way to do it than written.
for (var j = 0; j < compare.length; j++){
var searchTerm = compare[j]["a"];
for (var k = 0; k < objs.length; k++){
if (!objs[k].Found && objs[k]["a"] == searchTerm){
objs[k].Found = true;
break;
}
}
}

Why on earth is jack showing up in the sequence of alert boxes?

Object.prototype.jack = {};
var a = [1,2,3];
for(var number in a){
alert(number);
}
Could anyone tell me why the word "jack" jumped out of the alert box?
Thank you very much!
Simple - arrays are objects in javascript so by adding:
Object.prototype.jack={};
You've added an enumerable property 'jack' to all objects (and by that to all arrays).
once creating your array "a" and looping through all of its properties
for(var number in a)
You are sure to get a 'jack' alert. To avoid it showing up you can use .hasOwnProperty() to make sure all alerted properties are not inherited. or use a regular
for(var i=0; i < a.length; i++)
loop.
The for..in loop iterates over properties. It's only recommended (by Mozilla and other authorities) to be used on Objects, but not Arrays. If you insist, this is the correct way to iterate over an object and it will work for an array (most of the time).
for (var number in a) {
if (Object.prototype.hasOwnProperty.call(a, number)) {
alert(a[number]); // shows 1 then 2 then 3
}
}
To do it the generally accepted way,
for (var i=0; i<a.length; i++) {
alert(a[i]); // same as above
}
My personal preference is:
for (var val, i=0; val = a[i]; i++) {
alert(val); // same as above
}
Because you're not checking if jack is a property inherited from prototype or not. Try this instead:
Object.prototype.jack={};
var a = [1,2,3];
for (var number in a) {
if (a.hasOwnProperty(number)) {
alert(number);
}
}

Is there a method to set a typed array to zero?

Is there a way to set every element of a Javascript typed array (i.e. a Uint32Array) to some value (something like the C function memset would do)?
var foo = new Uint32Array(16384);
for (int i=0; i<foo.length; i++) { // I want to do this without a for-loop
foo[i] = 0xdeadbeef;
}
Generally, the answer in this case is going to be no. In JavaScript you either declare things fully when you create them via literal syntax:
var Arr1 = [1,2,3,4,5];
Or you assign values to them (via loops when necessary for sequences):
var Arr2 = Array(32);
for (var i = 0, j < Arr2.length; i < j; ++i) { Arr2[i] = 0xdeadbeef; }
JavaScript is a language that benefits from only accessing Arr2.length once when possible, so this syntax should net a performance benefit over other variations, but there's not a way to assign all positions in an array to a specific value other than undefined, which is what you get when you initialize with a size.

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