How do array sizes work in Javascript - javascript

In JavaScript, if you set an array to be of size 5 ( var foo = new Array(5); ), is this just an initial size? Can you expand the number of elements after it is created. Is it possible to do something like this as well - arr = new Array() and then just assign elements one by one? Thanks in advance :-)

Yes it is just an initial size, and it is not required. If you don't use a single number, you can immediately populate.
It is also more common to use the simpler [] syntax.
var arr = ['something', 34, 'hello'];
You can set (or replace) a specific index by using brackets:
arr[0] = "I'm here replacing whatever your first item was";
You can add to the end by using push:
arr.push('add me');
There may be faster performance in some browsers if you do it like this instead:
arr[arr.length] = 'add me';
You can add something at any index.
You can remove an item completely using splice:
arr.splice(0, 1); // remove first item in the array (start at index 0, with 1 being removed)

When you give a new array an explicit size in javascript (using new Array(5)), you populate each index with value of undefined. It is generally considered better practice to instantiate using the array literal [] expression:
var arr = [];
Then, you can push new elements using push()
var arr = [];
arr.push('first value'):
arr.push('second value'):
Check out the MDC Array documentation for more info: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array

Theres a few ways to declare and put values in an array.
First like what you want to do,
var myarr = new Array();
myarr[0] = 'element1';
myarr[1] = 'element2';
myarr[2] = 'element3';
Second way is to define them
var myarr =new Array("element1","element2","element3");
and third is similar to the second
var myarr =["element1","element2","element3"];
You can also check out https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array for a little more information about using the arrays as well. You could use push and pop if you wanted to as well.
If you use jquery or mootools they also have built-in functions to perform on arrays,
http://api.jquery.com/jQuery.each/ for instance.

Have a look at http://www.w3schools.com/js/js_obj_array.asp
var myCars=new Array(); // regular array (add an optional integer
myCars[0]="Saab"; // argument to control array's size)
myCars[1]="Volvo";
myCars[2]="BMW";

Check the documentation for Array, but the simple answer to your question is yes.
var arr5 = new Array(1, 2, 3, 4, 5); // an array with initial 5 elements
var arr = new Array(); // an array without initial
You can also use array literals:
var arr5 = [1, 2, 3, 4, 5];
var arr = [];

Arrays are dynamic in JavaScript. You don't have to initialize them with a certain length. In fact you should use the literal notation [] because of the Array constructor's ambiguity:
If you pass only one parameter to Array, it will set the array length to this parameter. If you pass more than one parameter, these elements are added to the array.
How is the size of the array determined?
The size of an array is the highest index + 1. This can be quite confusing. Consider this:
var arr = [];
arr[41] = 'The answer?';
console.log(arr); // [undefined, undefined, ..., 'The answer?']
console.log(arr.length) // 42
You can even set the length yourself by assigning a number to .length:
arr.length = 99;
If you now add a new element using arr.push(), it will get the index 100 and the length will increase. Whenever you add an element to the array via an index, it is tested whether arr.length is smaller than the index and updated accordingly. But it does not get smaller.
So in fact what var arr = new Array(5) is doing is setting the length of the array to 5. Nothing else.
For more information about creating and populating arrays, I suggest to read about it in the MDC JavaScript Guide.

Related

Assigning 'undefined' a value, how?

I was trying to assign a value to the items of an empty array, but I couldn't manage.
I used the Array constructor, and tried using both the .map() and the for ... of, but it didn't work.
let chrom = new Array(4);
const randomN = () => Math.floor(Math.random()*2);
for (g of chrom) {
g = randomN()
}
However, this solution worked
let emptyArr = new Array(4);
const randomN = () => Math.floor(Math.random()*2);
for (i=0; i<chrom.length; i++) {
chrom[i] = randomN()
}
Somehow it seems like only specifying the indexes does the trick.
does anybody know why this happens? what should I read? I tried looking in the documentation, but I couldn't see anything there.
The explanation is that in your first solution, g is going to be a local variable (a copy) instead of a reference to the actual value in the chrom array.
For example:
let nums = [1, 2, 3]
for (let num of nums) {
num = 1 // num in this case is a totally different variable
}
console.log(nums) // will still output [1, 2, 3]
Here is a good article explaining the difference between value vs reference in Javascript.
Using the for...of loop does not work since g is only a variable that holds the value of the element of the array at the current index; modifying it does not modify the array.
Array#map skips all empty slots, like those created by Array(size) or new Array(size). An array literal with an empty slot looks like this: [,]. You can fill the array before mapping or use spread syntax.
chrom.fill().map(randomN);
//or
[...chrom].map(randomN);
The standard index-based for loop uses the length of the array, which includes empty slots and sets elements using the index, so it has the desired effect.

How to initialize array length and values simultaneously in new Array()?

Let’s consider, I have to initialize an Array with some values
So I can achieve this by writing following code.
var arr = new Array("a", "b", "c", "d")
console.log(arr)
Similarly, I have to determine the length of the array before using it.
So I can achieve this by following code.
var arr = new Array(5)
console.log(arr.length)
Finally, I have a following questions ?
Is it possible to initialize an array with array length and different values (not similar values) simultaneously using new Array() ?
How to initialize a single integer value using new Array() ?
EDIT:
here, different values refers there are some specific string values.
I know it is straightforward when using array literals. but that's not exactly what I want.
The answer for both questions is no. Looking at the docs, there are two overloads for the Array function.
A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the Array constructor and that argument is a number (see the arrayLength parameter below).
If the only argument passed to the Array constructor is an integer between 0 and 232-1 (inclusive), this returns a new JavaScript array with its length property set to that number.
Only these two possibilities exist, there is no overload for specifying both the size and the values of an array.
You can create and fill an array like so:
let a = Array(100).fill(null)
console.log(a)
Or to increment your filled values:
let i=0,a = Array(100).fill(0).flatMap(x=>[x+i++])
console.log(a)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap
You could use .fill().
console.log(new Array(5).fill(2));
// [2, 2, 2, 2, 2]
Is it possible to initialize an array with array length and values simultaneously using new Array() ?
As far as I know, this isn't possible yet.
How to initialize a single integer value using new Array() ?
That would be k => new Array(1).fill(k). But if I had to choose, I'd use k => [k]. Note it is recommended not to use new Array() in other scenarios than to initialize it's lenght. But even then, you should rather be sure you are giving it an integer because the behaviour of new Array(n) is a bit erratic, and won't throw you an error when you wish it did.
Actually, I wish it was not possible to initialize an array with value using new Array(). The worst being using new Array(...args), whose behaviour will change dramatically when args is [5]. You should stick to [] arrays if you want to initialize an array with values.
Array("") gives [""]
Similarly Array([]) gives [[]] and Array({}), [{}]
Array(5) gives an array with 5 empty slots
Array(2.5) produces an Uncaught RangeError: Invalid array length.
Also, Array() gives []
Note: This is Chromium's behaviour. I didn't check Firefox.
There are few ways to create an array:
1) Literals
const a = [1,2,3];
console.log(a);
But you say you don't want to use it.
2) Array constructor:
const a = new Array(10); //array of length 10
console.log(a);
const b = new Array(1,2,3);
console.log(b); // array with elements 1,2,3
But you say that you don't want to go for it
3) Array.from
const a = Array.from(new Array(10), (val, ind) => ind); // array of 10 values and map applied to these elements
console.log(a);
Over these 3 ways, you have the Array.fill method, which can be called with static values only:
const a = new Array(10);
console.log(a.fill(5)); // array of 10 number elements with value of 5
Considering your case, maybe your solution could be to go with Array.from, using the map function you can provide as second parameter.
You could think to create some function like the following:
function createMyArray(length, start, end) {
return Array.from(new Array(length), (val, ind) => ind >= start && ind <= end ? ind : undefined);
}
console.log(createMyArray(5, 2, 4));
console.log(createMyArray(5, 1, 3));
console.log(createMyArray(10, 2, 6));
The question you should ask to yourself is: Where and how is the data I want to use coming from? Otherwise this is really too much vague
Is it possible to initialize an array with array length and different values (not similar values) simultaneously using new Array() ?
No you cannot do that with the Array constructor only.
An alternative way is to do it like this:
var a = ['a', 'b', 'c', 'd'];
a.length = 10;
console.log(a);
How to initialize a single integer value using new Array() ?
You can't. This is what happens when you try to do so according to the specification:
Array(len)
[...]
Let intLen be ToUint32(len).
If intLen ≠ len, throw a RangeError exception.
Let setStatus be Set(array, "length", intLen, true).
Assert: setStatus is not an abrupt completion.
Return array.
Use the other ways to create an array instead (e.g. [1] or Array.of(1)).
Here's a different but related take on initializing an array without using an array literal.
let arr = [...Array(10)].map((emptyItem, index) => index);
// [0,1,2,3,4,5,6,7,8,9]
I can't find documentation that matches how this expression is constructed, so I can't fully explain it. But it is using the spread syntax to spread 10 empty items into an array.

Select elements from a Javascript Array using one of the elements as a reference point

I'm wondering if it's possible to pull a certain number of elements out of a Javascript array and insert them into a new array, while using one of the elements as a reference point?
This is what I'm trying to do, imagine I have an array like this:
var firstarray = [
475387453,
286235425,
738264536,
196792345,
834532623,
253463455,
535273456];
And then I have a variable that equals the number 286235425:
var element = 286235425;
I have another variable that equals the number 3:
var thenumber = 3;
What I want to do is go through the array, select the 3 elements that come after the ''var element'' number, and store them in a new array named "second array".
So with the above example the result should be:
var secondarray = [
738264536,
196792345,
834532623];
I've seen some questions that talked about filtering array elements, but I haven't been able to find anything about selecting elements in the above way. Is such a thing even possible?
I know it's possible to trim elements from the beginning and end of the array, but as the array will always be a different length whenever the function runs, this method isn't suitable for this problem.
Any help with this would be really appreciated,
Thank you in advance!
You can do this with splice and indexOf
var firstarray = [
475387453,
286235425,
738264536,
196792345,
834532623,
253463455,
535273456
], element = 286235425, thenumber = 3;
var secondarray = firstarray.splice(firstarray.indexOf(element)+1, thenumber);
console.log(secondarray)
Grab the index where element is in the array using indexOf:
var index = firstarray.indexOf(element);
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
Use slice to grab the elements from the array from the next index to the next index + thenumber
var secondarray = firstarray.slice(index + 1, index + 1 + thenumber);
The slice() method returns a shallow copy of a portion of an array into a new array object.
DEMO

when push an element in sized array the array size is dynamically grow why?

i'm trying to push a string elements to sized array but when pushing an element the sized array start insert the elements in the last index of the array and grow but i want to insert the first element in the index [0] and second on [1] and so on till index [3] but i don't know why it start to insert elements after the last index and grow when add more element my code :
var users = new Array(3);
users.push(someData);
console.log(users);
console.log(users.length)
and the result like this:
[ , , , 'd', 'dd' ]
5
Avoid using new Array(count). Just create an empty array and then push to it like that:
var users = [];
users.push(someData);
Or, if you have some initial static content, this will be better:
var users = [ someData ];
The reason why I advise you to avoid new Array(...) is because it can be confusing and error-prone:
new Array(3) will create an array with 3 items: [undefined, undefined, undefined].
new Array(3, 4) will create an array containing the items 3 and 4: [3, 4].
Push adds a new element to the end of the array. You create the array with three empty entries then push somethign onto the end. Javascript does not have limited sized arrays. In your case I would guess you want to create an empty arraya nd just push onto it.
The argument you pass to the new Array call sets the initial size, not the maximum size. There is no max size. Just create the array like this:
var users = new Array()
or
var users = []
When you create an array with the constructor and specify a size, that will only set the current length of the array, it won't limit the size of the array.
Doing this:
var users = new Array(3);
does exactly the same thing as this:
var users = new Array();
users.length = 3;
Growing the array by setting the length doesn't actually put anything in the array, it will only set the length property.
The push method looks at the length property when it adds an item, so doing this:
users.push(someData);
does exactly the same thing as:
users[users.length] = someData;
If you want your array to be empty from the start, just create it without setting the length:
var users = new Array();
You can also use the array literal syntax to create an empty array:
var users = [];
Arrays doesn't support limiting the size, so if you want a collection with a limited size, you have to create it yourself (or find one that someone else has created).
array.push() method of array insert element from last index of array. use array.unshift() method to push from starting index of array
Because in javascript "var users = new Array(3);" means creation of array with 3 undefined elements.
For basic Array initialization details you can refer to : http://www.w3schools.com/js/js_arrays.asp

Array construction and negative numbers

I was implementing a routing algorithm in javascript, but when I assign a negative one variable in the array gives me this error: invalid array length.
var node = new Array()
node[0] = new Array(6,7)
node[1] = new Array(5,-4,8)
node[2] = new Array(-2) //Here, invalid array length
I do not know how to resolve this error.
If you are trying to initialize an array that contains only a negative number, use the literal syntax:
var a = [-2];
The problem with the Array constructor is that when it is invoked only with only one argument, this number is used as the length of the new array, e.g.:
var b = new Array(5);
b.length; // 5
I recommend you to stick with the literal syntax to avoid those ambiguities.
Don't declare arrays that way!
var node = [6, 7];
It's because one integer argument sets the size of new Array.
The array constructor documentation shows the following
var arr1 = new Array(arrayLength);
var arr2 = new Array(element0, element1, ..., elementN);
So, if you use only one parameter, it creates an array of arrayLength; otherwise, if you use more than one, it will populate the array with those values.
However, as others have pointed out, it is best use the literal notation *
var node = [
[6, 7],
[5, -4 8],
[-2]
];
* Array literal notation is slightly slightly faster than new Array(), but that's a micro optimization and not very important in most cases.

Categories

Resources