Related
I accidentally compared a large array and a number with <, and JavaScript locked up for over 5 seconds. What is the expected behavior of this comparison? Is it iterating over the whole array? MDN didn't clarify the situation.
As a concrete example, this code snippet takes over 5 seconds to print done:
var m = [];
m[268435461] = -1;
console.log('start');
if (m < 0) { }
console.log('done');
Javascript "arrays" (those with Array prototype, not typed arrays), are just objects, therefore this
var m = [];
m[268435461] = -1;
is exactly the same as
var m = {
"268435461": -1
}
except that in the first case, m has the Array prototype and a special length property.
However, methods defined in Array.prototype (like forEach or join) are trying to hide that fact and "emulate" sequential arrays, as they exist in other languages. When iterating their "this" array, these methods take its length property, increase the loop counter from 0 upto length-1 and do something with the value under the key String(i) (or undefined if there's no such key)
// built-in js array iteration algorithm
for (let i = 0; i < this.length - 1; i++) {
if (this.hasOwnProperty(String(i))
do_something_with(this[String(i)])
else
do_something_with(undefined)
Now, length of an array is not a number of elements in it, as the name might suggest, but rather the max numeric value of its keys + 1, so in your case, length will be 268435462 (check it!)
When you do m < 0, that is, compare a non-number to a number, JS converts them both to strings, and Array.toString invokes Array.join, which, in turn, uses the above loop to convert elements to strings and insert a comma in between:
// built-in js Array.join algorithm
target = '';
for (let i = 0; i < this.length - 1; i++) {
let element = this[String(i)]
if(element !== undefined)
target += element.toString()
target += ','
}
Illustration:
m = [];
m[50] = 1;
console.log(m.join())
This involves lots of memory allocations, and that's what is causing the delay.
(After some more testing, the allocation are not the deciding factor here, "hollow" loops will cause the same slowdown:
console.time('small-init')
var m = [];
m[1] = -1;
console.timeEnd('small-init')
console.time('small-loop')
m.forEach(x => null)
console.timeEnd('small-loop')
console.time('big-init')
var m = [];
m[1e8] = -1;
console.timeEnd('big-init')
console.time('big-loop')
m.forEach(x => null);
console.timeEnd('big-loop')
That being said, I don't think modern JS engines are that silly, and implement iterations exactly as described above. They do have array-specific optimizations in place, but these optimizations are targeted at "good" sequential arrays, and not at bizarre edge cases like this. Bottom line: don't do that!
I'm trying to make an array of empty arrays, the amount of which depends on N. Currently, I have this:
var seqList = [];
for(var i = 0; i < N; i++) {
seqList.push([]);
}
Is this the most efficient way of doing it? Or might there be another way?
Your method is the most efficient one. You can also use Array.fill method from ES6 but it is not the most efficient.
let n=10;
let array=Array.from({ length: n }, () => []);
console.log(array);
When you are using let array=[] you're telling the interpreter to create a new runtime array.
If you use:var a = new Array() you're telling the interpreterthat you want to call the constructor Array , generate an object and creating your array.
Array#fill is the cleanest
let count = 10;
let seqList = Array(count).fill([]);
Update:
After being schooled by #deceze I would rather use since the example above fails is a horribly subtle way.
let count = 10;
let seqList = Array(count).fill(0).map(_ => []);
Is it better than your attempt? Probably not. I've just become so used to reading map/reduce, I prefer it. YMMV
I am now practicing some methods in javascript, like shift(), unshift(), push(), pop(), and I want to write a little function that will take 3 arguments, an array, a start point, an end point. Which is used to cut a part of array out, and then return both the new array and the cut part. Not a useful thing or a big deal, just want to practice javascript.
But I encountered a strange thing, which I don't know why.
Here is the strange part
var a1 = [];
var a2 = [9,8,7,6,5,4,3,2,1];
for(var i=0; i<a2.length; i++){
a1.unshift(a2.shift())
}
So I wrote this code, and the expected result should be
a1 = [1,2,4,5,6,7,8,9]
a2 = []
However, when I run the code, this was what actually happened
a1 = [5,6,7,8,9]
a2 = [4,3,2,1]
It seems like the function was looped not enough time, so I tried to change the a2.length to a integer: 9
which make the code become
var a1 = [];
var a2 = [9,8,7,6,5,4,3,2,1];
for(var i=0; i<9; i++){
a1.unshift(a2.shift())
}
And that worked!
Then I change the approach to this
var a1 = [];
var a2 = [9,8,7,6,5,4,3,2,1]
var aLength = a2.length;
for(var i=0; i<aLength; i++){
a1.unshift(a2.shift())
}
And this worked too!!!
Could anyone tell me why is that ???
And how can I improve the loop?
Thank you very much, really appreciate for your time.
You could easily do this by using while loop
while (a2.length > 0)
{
a1.unshift(a2.shift());
}
The loop condition is re-evaluated for each iteration, and a2.length is constantly changing.
If you want to use its initial value, cache it beforehand:
var n = a2.length;
for (var i = 0; i < n; i++) {
a1.unshift(a2.shift());
}
Javascript Array: Shift() Method
The shift() method is like the pop() method, only it works at the
beginning of the array. The shift() method pulls the first element off
of the given array and returns it. This alters the array on which the
method was called.
So when you do a a2.shift() it will actually modify (decrease the number of elements in the array) the array and thus the effect
Do you think there is a big difference in for...in and for loops? What kind of "for" do you prefer to use and why?
Let's say we have an array of associative arrays:
var myArray = [{'key': 'value'}, {'key': 'value1'}];
So we can iterate:
for (var i = 0; i < myArray.length; i++)
And:
for (var i in myArray)
I don't see a big difference. Are there any performance issues?
The choice should be based on the which idiom is best understood.
An array is iterated using:
for (var i = 0; i < a.length; i++)
//do stuff with a[i]
An object being used as an associative array is iterated using:
for (var key in o)
//do stuff with o[key]
Unless you have earth shattering reasons, stick to the established pattern of usage.
Douglas Crockford recommends in JavaScript: The Good Parts (page 24) to avoid using the for in statement.
If you use for in to loop over property names in an object, the results are not ordered. Worse: You might get unexpected results; it includes members inherited from the prototype chain and the name of methods.
Everything but the properties can be filtered out with .hasOwnProperty. This code sample does what you probably wanted originally:
for (var name in obj) {
if (Object.prototype.hasOwnProperty.call(obj, name)) {
// DO STUFF
}
}
FYI - jQuery Users
jQuery's each(callback) method uses for( ; ; ) loop by default, and will use for( in ) only if the length is undefined.
Therefore, I would say it is safe to assume the correct order when using this function.
Example:
$(['a','b','c']).each(function() {
alert(this);
});
//Outputs "a" then "b" then "c"
The downside of using this is that if you're doing some non UI logic, your functions will be less portable to other frameworks. The each() function is probably best reserved for use with jQuery selectors and for( ; ; ) might be advisable otherwise.
there are performance differences depending on what kind of loop you use and on what browser.
For instance:
for (var i = myArray.length-1; i >= 0; i--)
is almost twice as fast on some browsers than:
for (var i = 0; i < myArray.length; i++)
However unless your arrays are HUGE or you loop them constantly all are fast enough. I seriously doubt that array looping is a bottleneck in your project (or for any other project for that matter)
Note that the native Array.forEach method is now widely supported.
Updated answer for 2012 current version of all major browsers - Chrome, Firefox, IE9, Safari and Opera support ES5's native array.forEach.
Unless you have some reason to support IE8 natively (keeping in mind ES5-shim or Chrome frame can be provided to these users, which will provide a proper JS environment), it's cleaner to simply use the language's proper syntax:
myArray.forEach(function(item, index) {
console.log(item, index);
});
Full documentation for array.forEach() is at MDN.
The two are not the same when the array is sparse.
var array = [0, 1, 2, , , 5];
for (var k in array) {
// Not guaranteed by the language spec to iterate in order.
alert(k); // Outputs 0, 1, 2, 5.
// Behavior when loop body adds to the array is unclear.
}
for (var i = 0; i < array.length; ++i) {
// Iterates in order.
// i is a number, not a string.
alert(i); // Outputs 0, 1, 2, 3, 4, 5
// Behavior when loop body modifies array is clearer.
}
Using forEach to skip the prototype chain
Just a quick addendum to #nailer's answer above, using forEach with Object.keys means you can avoid iterating over the prototype chain without having to use hasOwnProperty.
var Base = function () {
this.coming = "hey";
};
var Sub = function () {
this.leaving = "bye";
};
Sub.prototype = new Base();
var tst = new Sub();
for (var i in tst) {
console.log(tst.hasOwnProperty(i) + i + tst[i]);
}
Object.keys(tst).forEach(function (val) {
console.log(val + tst[val]);
});
I second opinions that you should choose the iteration method according to your need. I would suggest you actually not to ever loop through native Array with for in structure. It is way slower and, as Chase Seibert pointed at the moment ago, not compatible with Prototype framework.
There is an excellent benchmark on different looping styles that you absolutely should take a look at if you work with JavaScript. Do not do early optimizations, but you should keep that stuff somewhere in the back of your head.
I would use for in to get all properties of an object, which is especially useful when debugging your scripts. For example, I like to have this line handy when I explore unfamiliar object:
l = ''; for (m in obj) { l += m + ' => ' + obj[m] + '\n' } console.log(l);
It dumps content of the whole object (together with method bodies) to my Firebug log. Very handy.
I'd use the different methods based on how I wanted to reference the items.
Use foreach if you just want the current item.
Use for if you need an indexer to do relative comparisons. (I.e. how does this compare to the previous/next item?)
I have never noticed a performance difference. I'd wait until having a performance issue before worrying about it.
here is something i did.
function foreach(o, f) {
for(var i = 0; i < o.length; i++) { // simple for loop
f(o[i], i); // execute a function and make the obj, objIndex available
}
}
this is how you would use it
this will work on arrays and objects( such as a list of HTML elements )
foreach(o, function(obj, i) { // for each obj in o
alert(obj); // obj
alert(i); // obj index
/*
say if you were dealing with an html element may be you have a collection of divs
*/
if(typeof obj == 'object') {
obj.style.marginLeft = '20px';
}
});
I just made this so I'm open to suggestions :)
With for (var i in myArray) you can loop over objects too, i will contain the key name and you can access the property via myArray[i]. Additionaly, any methods you will have added to the object will be included in the loop, too, i.e., if you use any external framework like jQuery or prototype, or if you add methods to object prototypes directly, at one point i will point to those methods.
Watch out!
If you have several script tags and your're searching an information in tag attributes for example, you have to use .length property with a for loop because it isn't a simple array but an HTMLCollection object.
https://developer.mozilla.org/en/DOM/HTMLCollection
If you use the foreach statement for(var i in yourList) it will return proterties and methods of the HTMLCollection in most browsers!
var scriptTags = document.getElementsByTagName("script");
for(var i = 0; i < scriptTags.length; i++)
alert(i); // Will print all your elements index (you can get src attribute value using scriptTags[i].attributes[0].value)
for(var i in scriptTags)
alert(i); // Will print "length", "item" and "namedItem" in addition to your elements!
Even if getElementsByTagName should return a NodeList, most browser are returning an HTMLCollection:
https://developer.mozilla.org/en/DOM/document.getElementsByTagName
For in loops on Arrays is not compatible with Prototype. If you think you might need to use that library in the future, it would make sense to stick to for loops.
http://www.prototypejs.org/api/array
I have seen problems with the "for each" using objects and prototype and arrays
my understanding is that the for each is for properties of objects and NOT arrays
If you really want to speed up your code, what about that?
for( var i=0,j=null; j=array[i++]; foo(j) );
it's kinda of having the while logic within the for statement and it's less redundant. Also firefox has Array.forEach and Array.filter
A shorter and best code according to jsperf is
keys = Object.keys(obj);
for (var i = keys.length; i--;){
value = obj[keys[i]];// or other action
}
for(;;) is for Arrays : [20,55,33]
for..in is for Objects : {x:20,y:55:z:33}
Use the Array().forEach loop to take advantage of parallelism
Be careful!!!
I am using Chrome 22.0 in Mac OS and I am having problem with the for each syntax.
I do not know if this is a browser issue, javascript issue or some error in the code, but it is VERY strange. Outside of the object it works perfectly.
var MyTest = {
a:string = "a",
b:string = "b"
};
myfunction = function(dicts) {
for (var dict in dicts) {
alert(dict);
alert(typeof dict); // print 'string' (incorrect)
}
for (var i = 0; i < dicts.length; i++) {
alert(dicts[i]);
alert(typeof dicts[i]); // print 'object' (correct, it must be {abc: "xyz"})
}
};
MyObj = function() {
this.aaa = function() {
myfunction([MyTest]);
};
};
new MyObj().aaa(); // This does not work
myfunction([MyTest]); // This works
There is an important difference between both. The for-in iterates over the properties of an object, so when the case is an array it will not only iterate over its elements but also over the "remove" function it has.
for (var i = 0; i < myArray.length; i++) {
console.log(i)
}
//Output
0
1
for (var i in myArray) {
console.log(i)
}
// Output
0
1
remove
You could use the for-in with an if(myArray.hasOwnProperty(i)). Still, when iterating over arrays I always prefer to avoid this and just use the for(;;) statement.
Although they both are very much alike there is a minor difference :
var array = ["a", "b", "c"];
array["abc"] = 123;
console.log("Standard for loop:");
for (var index = 0; index < array.length; index++)
{
console.log(" array[" + index + "] = " + array[index]); //Standard for loop
}
in this case the output is :
STANDARD FOR LOOP:
ARRAY[0] = A
ARRAY[1] = B
ARRAY[2] = C
console.log("For-in loop:");
for (var key in array)
{
console.log(" array[" + key + "] = " + array[key]); //For-in loop output
}
while in this case the output is:
FOR-IN LOOP:
ARRAY[1] = B
ARRAY[2] = C
ARRAY[10] = D
ARRAY[ABC] = 123
In the following code sample i get a strange behavior
var data = ['xxx', 'yyy'];
for (var i in data)
{
var a = i;
var b = data[i];
}
The two first iterations works just fine. I get index "0" and "1" in i, but then it loops one extra time and now the i is "sum". Is this by design or what is this extra iteration used for? The result in my case is always empty and it messes up my code. Is there a way to not do his extra loop?
BR
Andreas
It looks like you (or some other code you've included) have added extra properties onto the Array prototype. What you should be doing is checking to see whether the object you're iterating over actually has that property on itself, not on its prototype:
for (i in data) {
if (data.hasOwnProperty(i)) {
a = i;
b = data[i];
}
}
That said, you should never use for .. in on arrays. Use a regular for loop.
See here for more information: http://yuiblog.com/blog/2006/09/26/for-in-intrigue/
You are looping through an Array, not through an Object. For arrays it's better to use:
for (var i=0; i<data.length; i=i+1){
/* ... */
}
In your loop every property of the Array object is taken into account. That makes the for ... in loop for array less predictable. In your case it looks like sum is a property (method) that's added to Array.prototype elsewhere in your code.
There are more ways to loop through arrays. See for example this SO-question, or this one
Just for fun, a more esoteric way to loop an array:
Array.prototype.loop = function(fn){
var t = this;
return (function loop(fn,i){
return i ? loop(fn,i-1).concat(fn(t[i-1])) : [];
}(fn,t.length));
}
//e.g.
//add 1 to every value
var a = [1,2,3,4,5].loop(function(val){return val+1;});
alert(a); //=> [2,3,4,5,6]
//show every value in console
var b = [1,2,3,4,5].loop(function(val){return console.log(val), val;});
Here's a way to safely iterate.
var data = ['xxx', 'yyy'];
for (var i = 0; i < data.length; i++)
{
var a = i;
var b = data[i];
}
What you are getting is an method coming from extending the Array object, I guess you are using some library where is something like
Array.prototype.sum = function () {...};
Perhaps setting data like this would work better: var data = {0:'xxx', 1:'yyy'};
First of all data is an object. Try to add console.log(a); and console.log(b); inside your loop and you'll see.