Javascript array element - javascript

We have a two by three array.Which means two rows three columns.Somwhere in the code I came accross this
var t = new Array( 2 );
t[ 0 ] = new Array( 3 )
t[ 1 ] = new Array( 3 );
t[0] is an element,right? In the zero position.
So this means that we create an element in the zeroeth position in the array of three elements? Or that we create said element in the array of three columns? How will the computer know 3 means 3 columns?

There are no multi dimensional arrays in Javascript, so you always use arrays of arrays (jagged arrays) for that.
When you create a jagged array you first create the outer array. Then you create an inner array for each item in the outer array.
In your example t[0] is the first item in the outer array, it's assigned the inner array.
Another way to create a jagged array is to use array literals, which may help visualise what they really look like:
var t = [
[ 0, 0, 0 ],
[ 0, 0, 0 ]
];

Calling the Array constructor with a number gives you an array initialized with its length property set to that number. It doesn't mean "3 columns" therefore; it just means an array whose length is 3.
JavaScript does not have real multi-dimensional arrays like C or FORTRAN do. An array is always a one-dimensional list of values. You can, however, put an array in a cell of another array, and that's what your code does. This:
var t = new Array(2);
creates an array whose length is 2. Then, the next two lines:
t[ 0 ] = new Array( 3 );
t[ 1 ] = new Array( 3 );
put new arrays of length 3 in each of the two cells of that array. It's now possible to use that assembly as if it were a real 2-dimensional array.
Note that what I mean by "real 2-dimensional array" is an array allocated as a single block of raw storage, row by row or column by column depending on the programming language. The distinction is important mostly for performance reasons, but flexibility is another consideration. It's possible in JavaScript to have an array of arrays such that the rows are not all the same length.

If you only need to know how many elements are in your jagged array, you can try t.length and t[0].length to find out. Like others already mentioned above, it's better to create an array with [ ] and elements can be defined in it or use push method to insert each element to it.

Related

How to create a 1d and a 2d array and how to initialize an array with a particular array size in Protractor?

I'm new to protractor. I want to create a 1d array and a 2d array and want to initialize the array by passing no.of rows and no.of columns like below
I'm mentioning Java array as an example
String[][] data=new String[2][3];
I want to know how to initialize the array in protractor like in Java. And it's better and knowledge-sharing for me by explaining the initialization of a 1d array also.
JavaScript is not a strongly typed language like Java, so arrays don't need to be initialized. However we can still initialize an array if we would like.
To create a 1d array use new Array:
let array = new Array(10) // An array with 10 items
You can then fill the array with a value using fill:
let array = new Array(10).fill('dog') // An array with 10 items with a value of dog
Taking the above, we can then initialize a 2d array by creating a new array with a set length and fill it with arrays. Since fill will take a value an use it once, we cannot pass new Array() to fill. We will need to map the first array and change it's value to an array. Map takes a function so we just return a new array from the map and it will replace the original values with an array.
The result looks like this:
function initArray(rows, cols, filler = null) {
return [...new Array(rows)].map(() => new Array(cols).fill(filler))
}
// create an array with all nulls
let arr = initArray(2, 3)
console.log(JSON.stringify(arr))
// Change a value in the array
arr[0][1] = 'dog'
console.log(JSON.stringify(arr))
// Create an array with a filler
console.log(JSON.stringify(initArray(5, 2, 'dog')))
Note: Remember that since this is javascript and not java, the size of the array is not set in stone, and it is 100% possible to push more items onto the array making it larger than the specified size without error and javascript will not complain.
First of all, If you are using protractor to automate your website then you must be using some language like 'java/ javascript / typescript', so its better that you search for "how to declare and initialize array in any of these languages.So for me im using typescript in my project so here it is :
var alphas:string[];
alphas = ["1","2","3","4"];
console.log(alphas[0]);
console.log(alphas[1]);`
https://www.tutorialspoint.com/typescript/typescript_arrays.htm

Javascript slice isn't giving me correct array length values

Why does it say length 1 instead of 4?
The following is what I'm trying to push and slice. I try and append items.image_urls and slice them into 5 each.
items.image_urls is my dictionary array.
var final_push = []
final_push.push(items.image_urls.splice(0,5))
console.log(final_push.length)## gives me 1...?
var index = 0
final_push.forEach(function(results){
index++ ##this gives me one. I would need 1,2,3,4,5,1,2,3,4,5. Somehting along that.
}
items.image_urls looks like this:
It's an iteration of arrays with image urls.
In your example items.image_urls.splice(0,5) returns an array of items removed from items.image_urls. When you call final_push.push(items.image_urls.splice(0,5));, this whole array is pushed as one item to the final_push array, so it now looks like [["url1", "url2", "url3", "url4", "url5"]] (2-dimensional array). You can access this whole array by calling final_push[some_index].
But what you want instead is to add every element of items.image_urls.splice(0,5) to the final_push. You can use a spread operator to achieve this:
final_push.push(...items.image_urls.splice(0,5));
Spread syntax allows an iterable such as an array expression or string
to be expanded in places where zero or more arguments (for function
calls) or elements (for array literals) are expected
This is exactly our case, because push() expects one or more arguments:
arr.push(element1[, ...[, elementN]])
And here is an example:
let items = {
image_urls: ["url1", "url2", "url3", "url4", "url5", "url6", "url7", "url8", "url9", "url10"]
};
let final_push = [];
final_push.push(...items.image_urls.splice(0,5));
console.log(final_push.length);
console.log(JSON.stringify(final_push));
console.log(JSON.stringify(items.image_urls));
Note: do not confuse Array.prototype.slice() with Array.prototype.splice() - the first one returns a shallow copy of a portion of an array into a new array object while the second changes the contents of an array by removing existing elements and/or adding new elements and returns an array containing the deleted elements.
That seems to be a nested array. So if you would access index 0, and then work on that array like below it will probably work:
console.log(final_push[0].length); //should print 4
The author is mixing up splice and slice. Probably a typo :)
You start at the beginning (0) and then delete 5 items.

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

Understanding syntax of multi dimensional array in javascript

var test = [[
[1,2],[2,3],[3,4]
]];
alert(test[[0]].length);
This returns me 3, but I cannot understand what this actually mean. How come this result?
There are no multi-dimensional arrays in JavaScript. There are only nested arrays.
[ // test
[ // test[0]
[1,2], // test[0][0]
[2,3], // test[0][1]
[3,4] // test[0][2]
] //
] //
As you can see, test[0] has a length of three.
And test[[0]] is semantically incorrect(*) and collapses into test[0].
(*) The index operator ([]) expects a number, like in test[0]. If you don't pass a number to it (like in your test[[0]] case, where you pass the array [0]), a conversion to string will happen first. (This is because of the first note below.)
Arrays are converted to string by joining their members with a comma. [0].toString() is "0", and therefore test[[0]] is equivalent to test["0"], which is equivalent to test[0].
Notes:
The square brackets are used for property access as well, so that test["length"] is the same as test.length.
Consequently, something horrible like test[[0]][["length"]]) is equivalent to test[0].length and will give you 3.
Something like test[[0,0]] would be test["0,0"] - and since there is no property named "0,0" on that array, you will get undefined.
The array test[0] contains three items:
[1,2]
[2,3]
[3,4]
Hence, the result of the length is 3.
The length of array test is just one, since test contains only one array:
[1,2],[2,3],[3,4]
In fact this is not a multi-dimensional array, it's just an array containing arrays (called a jagged array, or nested array).
test[[0]] is same thing as test[0] and test[0] is an array
[1,2],[2,3],[3,4]
consisting of these elements.
if you want to access ,for instance, [2,3] you need to use this syntax:
test[0][1]
and test[0][1].length will give you 2.
This is a nested array. An array of arrays.
It will be more clear if you expand your example:
var test = [
[
[1,2],[2,3],[3,4]
],
[
[5,6],[7,8],[9,9],[6,7]
],
];
alert(test[[1]].length);
Now, your test is an array of two arrays. The first one of which is an array of 3 arrays. The second one is an array of 4 arrays.
Now, test.length is 2. test[0].length is 3. test[1].length is 4. [[n]] just collapses.
Demo: http://jsfiddle.net/abhitalks/6H7Lj/
If you want get the length of first arrays length then write
alert(test[0][0].length);

using .slice method on an array

I'm practicing the array section of JavaScript Koan and I'm not fully understanding why these answers are correct. I added my assumptions below if someone could please clarify/let me know if I'm wrong :
it("should slice arrays", function () {
var array = ["peanut", "butter", "and", "jelly"];
expect(array.slice(3, 0)).toEqual([]);
Why wouldn't it at least slice "jelly" since the slice begins with
3? How does the cut off of 0 make it empty instead?
expect(array.slice(3, 100)).toEqual(["jelly"]);
If the cut off index goes beyond what currently exists in the array,
does this mean that a new array created from slice would contain all
indexes starting at 3 until the end of the array?
expect(array.slice(5, 1)).toEqual([undefined];
Will it always be undefined if the starting index doesn't exist in the
array?
});
The second argument to Array.slice() is the upper bound of the slice.
Think of it as array.slice(lowestIndex, highestIndex).
When you slice from index 3 to index 100, there is one item (in your case) that has index >= 3 and < 100, so you get an array with that one item. When you try to take a slice from index 3 to index 0, there can't be any items that meet the conditions index >= 3 and < 0, so you get an empty array.
--EDIT--
Also, array.slice() should never return undefined. That's one of the advantages of using it. If there are no matching values in the array, you just get back an empty array. Even if you say var a = new Array() and don't add any values to it, calling a.slice(0,1) will just give you an empty array back. Slicing from outside of the array bounds will just return an empty array also. a.slice(250) will return [] whereas a[250] will be undefined.

Categories

Resources