Why can't we provide size of array in Javascript? - javascript

Why can't we provide size of array in JavaScript?
I mean even if it is possible why don't we why we just simply define the array.

Because standard arrays in JavaScript aren't really arrays at all (spec | post on my blog), they're just objects backed by Array.prototype with special handling for a class of property names ("array indexes"), a special length property, and a built-in literal notation. They aren't contiguous blocks of memory as in some other languages (barring optimization, of course).
I have a question in my mind about why can't we provide size of array in JavaScript ??
You can create an array with a given length via Array(n) where n is the length as a number. But again, it doesn't preallocate memory for that many slots or anything. You just end up with a sparse array with length set to n and no entries in it:
var a = Array(42);
console.log(a.length); // 42
console.log(0 in a); // false, it doesn't have an entry 0
a.forEach(function(entry) { // Never calls the callback
console.log(entry); // because the array is empty
});
I mean even if it is possible why don't we why we just simply define the array.
Because it serves no purpose.
Now, for typed arrays (Uint8Array and similar), we do indeed create them with a specific length (var a = new Uint8Array(42);), and that length is fixed (cannot change), because they're true arrays.

You can provide size of array. If its not given, you can add multiple values dynamically.
var arr = new Array(5);

You can provide size of array in java-script.
Java-script array is different from array in C language.
You can read more on following link
understanding-javascript-arrays

You can provide a size of an array and that size of an array will not change in the program.
Array is an object backed by Array.prototype, so there is a function called seal.
var myArray = Object.seal([5, 6, "saurabh", "text"]); // this is an array of size 4 fixed.
//myArray.push('new text'); //throw exception error
console.log(myArray[2]); //"saurabh"
myArray[0] = "change text";
console.log("print myArray: ", myArray);
You can read more over here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal

Related

Weird Array Objects - JavaScript

Arrays are quite something in JavaScript when compared with other programming languages and it's not without its full set of quirks.
Including this one:
// Making a normal array.
var normalArray = [];
normalArray.length = 0;
normalArray.push(1);
normalArray[1] = 2;
normalArray; // returns [1, 2]
normalArray.length // returns 2
So yes, the above is how we all know to make arrays and fill them with elements, right? (ignore the normalArray.length = 0 part for now)
But why is it that when the same sequence is applied on an object that's not purely an array, it looks a bit different and its length property is off by a bit?
// Making an object that inherits from the array prototype (i.e.: custom array)
var customArray = new (function MyArray() {
this.__proto__ = Object.create(Array.prototype);
return this
});
customArray.length = 0;
customArray.push(1);
customArray[1] = 2;
customArray; // returns [1, 1: 2]
customArray.length // returns 1
Not entirely sure what's going on here but some explanation will be much appreciated.
This may not be the perfect answer, but according to my understanding of Javascript arrays, they are a little bit different than usual objects. (Mainly due to the fact that it maintains a length property, and Objects don't).
So if we take your code for an example:
var normalArray = [];
This is the right way to create an array in Javascript. But what about the below one?
var customArray = new (function MyArray() {
this.__proto__ = Object.create(Array.prototype);
return this
});
Are they same? Let's see..
Array.isArray(normalArray); // true -> [object Array]
Array.isArray(customArray); // false -> [object Object]
So it is clear that although you inherit from the array prototype, it doesn't really create an object with Array type. It just creates a plain JS object, but with the inherited array functions. That's the reason why it updates the length when you set the value with customArray.push(1);.
But since your customArray is only a regular object and for a regular JS object, [] notation is used to set a property, it doesn't update the length (because Objects don't have a length property)
Hope it's clear :)
The array you are trying to create is not a pure array (as you are perhaps aware). Its basically a JavaScript object and is supposed to behave like an object.
While treating an object like an array, its up to you to maintain all it's array like features.
You specifically have to assign a length property to it and you did it correctly.
Next, the push method from Array.prototype is supposed to insert an element to the array and increment the length property (if any), so it did increment 0 to 1. There you go, the length now is 1.
Next you used the literal notation of property assignment to Object, which is similar to something like customArray['someProperty'] = 1.
While using literal notation, no method from Array.Prototype is being invoked and hence the customArray object never knows that it has to behave like an Array and its length property remains unaffected. It simply behaves like an object and you get what you got.
Remember the length is just a property on Array class and this property is appropriately incremented and decremented by every method on Array.
Note: Array like objects are not recommended and its up to you entirely to maintain the index and other Array stuff for such objects.
From what I can see, you have a problem with your function:
return this
This should be
return (this);
Just fixes any potential errors you might have. Another thing is you're not using the var keyword to declare customArray. These errors might be breaking your code.

javascript array indexing with large integers

I have a strange problem. I need a multidimensional javascript array that has numeric indexes e.g.:
MyArray = new Array();
$(".list-ui-wrapper").each(function(){
var unique = $(this).attr('id').replace(/[^\d.]/g,'');
MyArray ["'"+unique+"'"] = new Array();
});
The unique is a 8 digit integer. So if I dont wrap it inside the quotes, the ListUI_col_orders array will become extremly big, because if the unique = 85481726 then javascript will fill the array with 85481725 undefined elements before the the new empty array at the 85481726th index.
My problem is that later if i generate the unique again i cannot access the array anymore:
var unique = $(this).attr('id').replace(/[^\d.]/g,'');
console.log(MyArray [unique]); // undefined
console.log(MyArray ['"'+unique+'"']); // undefined
console.log(MyArray [unique.toString()]); // undefined
Any tips?
If you are going to use an array that's mostly sparse, then use a Hash table instead.
eg, set your variable as follows:
ListUI_col_Orders = {};
Then your indexing will be a key, so you don't have to worry about all the interstitial elements taking up space.
...because if the unique = 85481726 then javascript will fill the array with 85481725 undefined elements before the the new empty array at the 85481726th index.
No, it won't. JavaScript standard arrays are sparse. Setting an element at index 85481725 results in an array with one entry, and a length value of 85481726. That's all it does. More: A myth of arrays
The problem is that you're trying to retrieve the information with a different key than the key you used to store it. When storing, you're using a key with single quotes in it (actually in the key), on this line of code:
MyArray ["'"+unique+"'"] = new Array();
Say unique is 85481726. That line then is equivalent to this:
MyArray ["'85481726'"] = new Array();
Note that the key you're using (the text between the double quotes) has ' at the beginning and end. The actual property name has those quotes in it. Since it doesn't fit the definition of an array index, it doesn't affect length. It's a non-index object property. (How can you add a property to an array that isn't an array index? Arrays are not really arrays, see the link above.)
Later, you never use that key when trying to retrieve the value:
var unique = $(this).attr('id').replace(/[^\d.]/g,'');
console.log(MyArray [unique]); // undefined
console.log(MyArray ['"'+unique+'"']); // undefined
console.log(MyArray [unique.toString()]); // undefined
The keys you tried there were 85481726, "85481726" (with double quotes), and 85481726 again. Note that you never tried '85481726' (with single quotes), which is the key you used originally. Since you didn't use the same key, you didn't get the value.
Either use consistent quotes, or (much better) don't use quotes at all. Don't worry about the array length being a large number, JavaScript arrays are inherently sparse. Adding an entry with a large index does not create several thousand undefined entries in front of it.
All of that being said, unless you need the "array-ness" of arrays, you can just use an object instead. Arrays are useful if you use their features; if you're not using their array features, just use an object.
More about the sparseness of arrays: Consider this code:
var a = [];
a[9] = "testing";
console.log(a.length); // 10
Although the length property is 10, the array has only one entry in it, at index 9. This is not just sophistry, it's the actual, technical truth. You can tell using in or hasOwnProperty:
console.log(a.hasOwnProperty(3)); // false
console.log("3" in a); // false
When you try to retrieve an array element that doesn't exist, the result of that retrieval is undefined. But that doesn't mean there's an element there; there isn't. Just that trying to retrieve an element that doesn't exist returns undefined. You get the same thing if you try to retrieve any other property the object doesn't have:
var a = [];
a[9] = "testing";
console.log(a[0]); // undefined
console.log(a[200]); // undefined
console.log(a["foo"]); // undefined
Final note: All of this is true of the standard arrays created with [] or new Array(). In the next spec, JavaScript is gaining true arrays, created with constructors like Int32Array and such. Those are real arrays. (Many engines already have them.)

Why do arrays behave this way when I add named properties?

I did following experiment in browsers console
I created a new Array.
Added "foo" to the Array as named index "name".
Added "bar" to the Array using push method.
4 & 5 are tests on the Array
1. var myArray = []; // undefined
2. myArray["name"] = "foo"; // "foo"
3. myArray.push("bar"); // 1
4. myArray.join(", "); // "bar"
5. myArray["name"]; // "foo"
My questions (what I didn't understand)
.push() returns 1 which is the length of the Array, but it must be 2 as the Array has two values "foo" & "bar"
Test 4 shows that the Array has only one value "bar" but test 5 oppose it showing that it also has a value "foo".
Why doesn't Array methods (push, join etc) works on key/value pairs ?
Then how does associative Array works and how we can handle it(methods, properties etc).
.push() returns 1 which is the length of the Array, but it must be 2 as the Array has
two values "foo" & "bar"
No, because arrays in JavaScript are not associative data structures (even though you can attach arbitrary properties to them). The only items that count as "array contents" are those whose property names satisfy certain conditions.
You should also be aware that length may also report a number greater than what you expect if the array has "holes". For example:
var a = [1, 2, 3];
console.log(a.join(" "), a.length); // "1 2 3", 3
delete a[1];
console.log(a.join(" "), a.length); // "1 3", still 3!
Test 4 shows that the Array has only one value "bar" but test 5 oppose it showing that it also has a value "bar".
That's irrelevant. The array also has many other properties, but join will only touch those mentioned earlier.
Why doesn't Array methods (push, join etc) works on key/value pairs ?
Because that's what the spec says.
Then how does associative Array works and how we can handle it(methods, properties etc).
Use a plain object instead of an array if you want string keys.
JavaScript doesn't really have associative arrays. Being able to do myArray["foo"] = "bar" is a side effect of arrays simply being objects, and objects having properties.
Only numeric properties count as elements of the array. If you do myArray["foo"] = "bar" you are not adding an element to the array, you're simply adding a property to the object. That's different to doing myArray[0] = "bar" which is adding an element, and will accordingly update the length property of the array object.
In JavaScript you cannot address array elements with a string, only integers. So,
1. var myArray = []; // undefined
2. myArray["name"] = "foo"; // "foo"
3. myArray.push("bar");
myArray will only contain "bar" since it ignores myArray["name"] = "foo"; which is why you get length 1.
Just like functions, Arrays are objects. But there are many Array prototype functions which purposefully do not access the properties of object. There is no 'associative array' in JavaScript, other than object and arrays depending on the function or code can behave or be leveraged in the same way you would use an associative array. You will encounter the same confusion in for loops when iterating over object key/pairs vs array values. In general though they are quite effective, there is a good book called Java Script the good parts. Which also then highlights the features or 'bad parts' to avoid or are dangerous. Googling about the sharp edges of objects and arrays in Javascript yields some good reads. They are not complex, but you do have to understand the more subtle ways Java is not like JavaScript.
Arrays in Javascript are not meant to be associative - when you add a property via a key you're actually adding it to the array object, not to the array itself.
If you want a key:value pair, use an Object

Creating multi-dimensional arrays in javascript, error in custom function

I was trying to define an array (including other arrays as values) in a single javascript statement, that I can loop through to validate a form on submission.
The function I wrote to (try to) create inline arrays follows:
function arr(){
var inc;
var tempa = new Array(Math.round(arguments.length/2));
for(inc=0; inc<arguments.length; inc=inc+2) {
tempa[arguments[inc]]=arguments[inc+1];
}
return tempa;
}
This is called three times here to assign an array:
window.validArr = arr(
'f-county',arr('maxlen',10, 'minlen',1),
'f-postcode',arr('maxlen',8, 'minlen',6)
);
However in the javascript debugger the variable is empty, and the arr() function is not returning anything. Does anyone know why my expectations on what this code should do are incorrect?
(I have worked out how to create the array without this function, but I'm curious why this code doesn't work (I thought I understood javascript better than this).)
Well from what your code does, you're not really making arrays. In JavaScript, the thing that makes arrays special is the management of the numerically indexed properties. Otherwise they're just objects, so they can have other properties too, but if you're not using arrays as arrays you might as well just use objects:
function arr(){
var inc;
var tempa = {};
for(inc=0; inc<arguments.length; inc=inc+2) {
tempa[arguments[inc]]=arguments[inc+1];
}
return tempa;
}
What you're seeing from the debugger is the result of it attempting to show you your array as a real array should be shown: that is, its numerically indexed properties. If you call your "arr()" function as is and then look at (from your example) the "f-county" property of the result, you'll see something there.
Also, if you do find yourself wanting a real array, there's absolutely no point in initializing them to a particular size. Just create a new array with []:
var tempa = [];
Your code works. Just inspect your variable, and you will see that the array has the custom keys on it. If not expanded, your debugger shows you just the (numerical) indixed values in short syntax - none for you.
But, you may need to understand the difference between Arrays and Objects. An Object is just key-value-pairs (you could call it a "map"), and its prototype. An Array is a special type of object. It has special prototype methods, a length functionality and a different approach: to store index-value-pairs (even though indexes are still keys). So, you shouldn't use an Array as an associative array.
Therefore, their literal syntax differs:
var array = ["indexed with key 0", "indexed with key 1", ...];
var object = {"custom":"keyed as 'custom'", "another":"string", ...};
// but you still can add keys to array objects:
array.custom = "keyed as 'custom'";

Which takes less memory: a Javascript array or Javascript object?

If I have a Javascript list which will have only numeric keys, which takes less memory?
var array = [];
array[0] = 'hello';
array[5] = 'world';
array[50] = 'foobar';
var obj = {};
obj[0] = 'hello';
obj[5] = 'world';
obj[50] = 'foobar';
I don't know a ton about Javascript engine internals, so...
The reason I ask is because that array, when converted to a string, will have a bunch of undefined's in the middle of it. Are those actually stored in some fashion, or is that just put in at string conversion?
An array is basically an ordered set of values associated with a single variable name.
In your example I think you try to do an associative array, and you should use object, Array is not meant to be used for key/value pairs.
Also the array length is indirecly increased when you assign a value to an index with higher length of the current array length:
var array = new Array();
array[99] = "Test";
// array.length is now 100
Check this detailed article on the subject.
Probably the Javascript array because you can 'only' use numeric key values, where as the object literals provide a space for key values, and even if you use numerical key values, they are probably handled differently than the numerical key values for arrays.
Most likely the reason arrays can't have text-based key values are because they are treated differently than object literals. I'm guessing that because they are probably treated differently, the processing for the array probably is more optimized for numeric key values, were as a object literal is optimized to use strings or numbers as their keys.
JavaScript doesn't implement arrays like other languages so you don't get any performance enhancements inherent of a normal array (memory-wise); in JavaScript an array is very similar to an object; actually, it is essentially an object just with a few extra methods and capabilities (such as a length that updates itself). I'd say neither is quicker.

Categories