Thursday, November 10, 2016

javascript: Avoid new Array(), Use [] instead.

var points = new Array(); // Bad
var points = []; // Good
var points = new Array(40, 100); // Creates an array with two elements (40 and 100)
var points = new Array(40); // Creates an array with 40 undefined elements !!!!!

http://www.w3schools.com/js/js_arrays.asp

How to Recognize an Array?
The typeof operator returns object because a JavaScript array is an object.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
typeof fruits; // returns object

Solution 1:
To solve this problem ECMAScript 5 defines a new method Array.isArray():
Solution 2:function isArray(x) {
return x.constructor.toString().indexOf("Array") > -1;
}
it returns true if the object prototype contains the word "Array".
Solution 3:The instanceof operator returns true if an object is created by a given constructor:
fruits instanceof Array // returns true

No comments:

Post a Comment