Convert a number (i. e. 5) to length of an array - javascript

I want to create a property on a polymer custom element that let's the user define a number of elements to repeat.
<my-element repeated-elements='5'></my-element>
This should tell my element to repeat the element inside of the component five times. For that I need an array with length of 5, so anything like this would do:
['','','','','']
Is there a way to do this in JavaScript? The number would be passed as a number, not a string. So somehow I would need to convert any number to the amount of array items in an array. Metaphorically speaking:
convertToArrayLength(5);
I'm completely lost here, I have no idea at all how this could be done.

The array constructor does exactly that:
var arr = Array(5);
console.log(arr, arr.length);
//=> Array [ <5 empty slots> ] 5
You don't need to put new before calling Array (just a peculiarity of the API).
Note though that arrays in JavaScript are dynamic, so most of the time you don't need to specify the length of your array beforehand and can simply initialize your variable with:
var arr = [];
// And then push to it as you go:
arr.push(x);

JavaScript will re size the array automatically as you push to it.
var array = new Array(5); // undefined
array.length; // 5
array.push("FOO"); // 6
array.length; // 6
All you have to do is make sure you assign the variable as an Array with either [] or new Array

Related

Blank Array Returned A Length of 5

I have been watching PluralSight's Rapid JavaScript Training by Mark Zamoyta and I came across this. He showed these two examples. I've been trying to wrap my head around it, but still could not understand.
How is it able to capture the length of the entries after the array was created using new Array() method, seeing that it returned a blank array []. If it's blank like this [], shouldn't it return -1?
var entries = [1,2,3,4,5];
entries.length
=> 5
entries
=> [ 1, 2, 3, 4, 5 ]
var entries = new Array(5);
entries.length
=> 5
entries
=> []
var myArray = new Array(5);
When you define an array by passing the constructor an integer like above, memory is allocated for 5 slots in the array. If you examine the array, you will find:
console.log(myArray[1]);
=> undefined
console.log(myArray.toString);
=> ,,,,
As you can see, there are indeed five elements in the array, each of them undefined. So your array isn't "blank."
It is probably bad practice to initialize an array in this manner, as there just isn't a good use case for it. Pushing to the array will yield:
myArray.push("value");
console.log(myArray.toString);
=> ,,,,,value
...which is never what you want. I would advise initializing the array like below and forget that passing an integer to the constructor is even an option:
var myArray = [];
The length property of an array in JS is not calculated on the fly - it can also be set manually via the constructor or an assignment, and it's updated as objects are added or removed (Spec):
Specifically, whenever a property is added whose name is an array index, the length property is changed, if necessary, to be one more than the numeric value of that array index[.]
It's a plain property that's kept up-to-date, not a calculation. Using the constructor new Array(5) initializes an array with length set to 5. You can also set it manually, which fills in undefined or truncates the array as needed:
var arr = [];
arr.length = 3;
// arr is now [undefined, undefined, undefined]

Empty Array in javascript

I created an object which contains an array.
I noticed that when I dont enter any values into the array, it still has one - its size,
So how can I check if the array is actually empty?
Here's how I'm creating the array:
array = { text:[10] }
The size of the array is not an array entry (aka array "element"). It is a property, length, but it's not an entry. An empty array is exactly that: empty.
The code you posted in a comment:
array = { text:[10] }
does not create an empty array. It creates an array of length 1 with the entry 10 in it.
If you want to create an empty array with a specific length, you can't do that in a single statement with an array literal ([]). You have two ways you can do it:
Using an array literal and assigning to length:
var a = [];
a.length = 10;
or using new Array:
var a = new Array(10);
But there's virtually never any reason, in JavaScript, to predefine the length of the array, because standard JavaScript arrays aren't really arrays at all. It does make sense with the new typed arrays (Uint32Array and such), and to do it you have to use the array constructor (new Uint32Array(10)).

Javascript two dimensional arrays [duplicate]

This question already has answers here:
How can I create a two dimensional array in JavaScript?
(56 answers)
Closed 8 years ago.
I have declared a two-dimensional array, like so:
a = [[]]
However, when I try to give a second dimension value using a first dimension index other than 0, it doesn't work:
a[1][0] = "foo" //returns error
Is there a better way around this than manually defining every index you need as an array, i.e.:
a[1] = [];
a[2] = [];
a[3] = [];
//et cetera
N-Dimensional arrays do not exist in javascript - you have to just make arrays containing arrays as elements.
You're getting an error because a = [[]]; declares an array with one element, which happens to also be an array. Therefore a[0] is the internal array, but a[1] does not exist because you never declared it. The easiest way to properly declare a "two dimensional array" would be to use a loop:
var outerArray = [];
var numInternalArrays = 5;
for (var i = 0; i < numInternalArrays; i++) {
outerArray[i] = [];
}
If you know how many elements the root array should have you could do something like this:
var arr =
(Math.pow(2,10)-1).toString(2) // Binary string of 1s. Its length being 10
.split('') // Create an array from this string
.map(function(){return [];}); // Map a new empty array to each index
console.log(arr); // [[],[],[],[],[],[],[],[],[],[]]
This accomplishes the same thing:
for(var arr = [], i=10; i--; arr[i]=[]);
No need to declare arr outside of the for-loop since javascript doesn't have block scope, it will be added to the scope in which it is executed.
a = [[]]
This is an Array, with the first item being an array. Which is why indexing into the first item still works (a[0][0]).
If you want to access the second item as an array, you need to create your array as
a = [[],[]]
See this question for examples of
How can I create a two dimensional array in JavaScript?
If I understand correctly, use a loop:
for (var i = y; i--; a[i] = []);
There are no multidimensional arrays in javascript.
What you are doing is an array of arrays, but the outermost array has only one element (i.e. element 0) whose value is another array. So a[1] (or more generally a[1][x]) is invalid since the outermost array has only one element.
So you can do a[0][x] = "foo" but not the other way around.
So you can either initialize the array with a for loop or do something like var a =[[][][][][]];
You can have the array of arrays start as in:
var a = []; // start with the column array
Then when you want to put something in location [i][j] we can call 'i' the row-index and 'j' the column-index.
if (!a[i]) { // check for row existing
a[i] = []; // .. and create it if not
}
a[i][j] = 'foo'; // put something in the array cell
Note that this only works because we are always putting something in the new row array right after we create it. It might not work if you put 0 or "" in there instead of 'foo'.
There are a lot of things in javascript that are 'false' including 'null' and 'undefined' and '0' and I just don't know if an empty array or an array with one element that is an empty string are considered false. So you would have to do some experimenting with how, exactly to detect a missing row array so you can add it in.

Initialize an array whose indexes are scattered over integer range

How to initialize a string array (size<100 items) in javascript whose indexes are scattered over entire integer range, with data items.
If I do like this:
array1 = ["string1","string2","string3","string4"];
then I get array of length 4 with indices ranging 0 to 3
But in my case i want to keep my own indices, so that the array could be used like a high performance int-string hash table.
I'm preferably looking out for a single statement initialization.
The items of the array should be accessible like this: array1[23454]
Update From Comments
I'm restricted to initialize the array as a single statement since a dynamically prepared array initialization string is appended from server side like this: var array = <string from server here>
To create an array with a set number of indexes you can use
// Creates an array with 12 indexes
var myArray = new Array(12);
This isn't needed in javascript due to the way its array's work. There isn't an upper-bound for arrays. If you try to reference an item index in the array that doesn't exist, undefined is returned but no error is thrown
To create an array with perscribed indexes you can use something like array['index'] = value though this would force you to use multiple statements. Javascript doesn't have an array initalizer to allow for you to specify indexes and values all in a single statement though you can create a function to do as such
function indexArray(param) {
var a = [], i;
for (i=0; i<param.length; i+=1) {
a[param[i].index] = param[i].value;
}
return a;
}
var myArray = indexArray([
{ index: 123456, value : "bananas" },
{ index: 12, value : "grapes" },
{ index: 564, value : "monkeys" }
]);
var array1 = []
array1[23454] = 2
Just doing this should be fine. There's no set array size for javascript in the way there is for java.
If you really want to do this all in a single statement, you can make an object instead like this:
var object1 = {
"23454":2,
"123":1,
"50":3
};
and then retrieve the numbers like this:
object1["23454"] //2
I don't really recommend this though. The array method is a cleaner way of doing it even if it takes multiple lines since it doesn't require string conversion. I don't know enough about how these are implemented in browsers to comment on the performance impact.
Update
Since the 1 line requirement is based on something being passed to the server, I would recommend passing a JSON object to the server in the form:
"{"23454":2,"123":1,"50":3}"
then this code will parse it to an object:
var object1 = JSON.parse(jsonstringfromserver);
and if you like you can always convert that to an array by enumerating over the properties with a for in loop:
var array1 = []
for ( num in object1){
array1[num] = object1[num];
That is probably unnecessary though since object1[123] will already return 1. You only need this if you plan on doing array specific operations.
You don't have to pre-define the size of an array before you assign to it. For example:
var _array = [];
_array[0] = "foo";
_array[1000] = "bar"; // _array.length => 1001
_array[1] //undefined
No need to initialise the appropriate number of array elements before you assign to them.
Update
It already has been pointed out that you can use an object rather than an array. However, if you want to take advantage of array methods then this is still possible. Let me give you an example:
var obj = {
0: 15,
1: 10,
2: 5,
length: 3
};
If the object contains a length property then it can be treated as an array-like object. Although you can't call array methods directly from these objects you can use array methods.
Array.prototype.join.call( obj ); // 15,10,5
In fact using the ECMAScript 5 map function you can easily convert the above object to an array.
var _array = Array.prototype.map.call( obj, function( x ) { return x; } );
The map function does not exist in all browsers but you can use the following function if it doesn't.
Array.map = Array.map || function(a, f, thisArg) {
return Array.prototype.map.call(a, f, thisArg);
}
You can do what you want with an Object in this way:
var o = {23454: 'aaaa', 23473: 'bbb'};
You will lose the array methods/fields, e.g. length, but you will gain what you said you are looking for, and you will be able to add/remove members easily.

Javascript array best practice to use [] instead of new array?

I read at many tutorials that the current best practices to create a new javascript array is to use
var arr = []
instead of
var arr = new Array()
What's the reasoning behind that?
It might be because the Array object can be overwritten in JavaScript but the array literal notation cannot. See this answer for an example
Also note that doing:
var x = [5];
Is different than doing:
var x = new Array(5);
The former creates an initializes an array with one element with value of 5. The later creates an initializes an array with 5 undefined elements.
It's less typing, which in my book always wins :-)
Once I fixed a weird bug on one of our pages. The page wanted to create a list of numeric database keys as a Javascript array. The keys were always large integers (a high bit was always set as an indicator). The original code looked like:
var ids = new Array(${the.list});
Well, guess what happened when the list had only one value in it?
var ids = new Array(200010123);
which means, "create an array and initialize it so that there are 200 million empty entries".
Usually an array literal(var a=[1,2,3] or a=[]) is the way to go.
But once in a while you need an array where the length itself is the defining feature of the array.
var A=Array(n) would (using a literal) need two expressions-
var A=[]; A.length=n;
In any event, you do not need the 'new' operator with the Array constructor,
not in the way that you DO need 'new' with a new Date object, say.
To create Array without Length
var arr = [];
To create Array with Length more dynamically
var arr;
( arr = [] ).length = 10; // 10 is array length
To create Array with Length less dynamically
var arr = [];
arr.length = 10;

Categories