How array of 2 has length 2? - javascript

As it's common arrays in js if you put 3 elements in array it will has length 3 but if I make array with only number two, it has length 2 ?!
const myArry=new Array(2)
console.log(myArry.length) // 2

new Array(2) means "make me an array with two empty slots". So yes, it has length 2.
You may be looking for const myArry = [2] which has length 1.
EDIT
Just for fun, if you really wanted to use constructor syntax instead of array literal syntax (the [2] part), you could do:
new Array(1).fill(2)
Which actually could make sense if both the length and the fill value were dynamic parameters.

Related

why does javascript parse an array as a string when passed in as an argument or as an index

consider this code
example 1:
function plus(a) {return a+10}
([1]) // "110"
example 2:
var arr = [1,2,3,4,5,6,7]
arr[[1]] // 2
arr.splice([1],1);
arr // (6) [1, 3, 4, 5, 6, 7]
can someone explain why passing in an array as an argument, gets converted to a string? (that's what it looks like happened here)
can someone explain why passing in an array as an argument
It doesn't.
It gets treated as an array right up until the point where you try to use the addition operator on it.
It hits the step Let rprim be ? ToPrimitive(rval) and converts it according to those rules.
And so on until it calls the array's toString method.
Similar rules apply in the other examples.
In short: When it makes no sense at all to use an array in a given context, type conversion is applied to turn it into a data type that is apropriate.
Javascript automatically outputs a certain data type when two different data types are added.
Here are two examples:
2 + 3 // 5
2 + "hello" // "2hello"
When two numbers are added, an integer is output. However, 2 and hello can't be added numerically, so everything is first automatically converted to a string, and then appended.
The same thing happens in your case – a remains an array, but an array can't be added to a number. So both are converted to strings and then appended, and the end result is a string.
You were probablly thinking of adding a value to the end of an array. This is done using:
a.push(10);
Or, if you wanted to add the first item in the array and 10 to get the result 11, use:
return a[0] + 10
But you can't add a single number to a whole array, only to one of the items or at the end of the array.
Answer #1 - you get a string from the array.toString so you need to cast back to number - here I use +
function plus(a) {return +a+10}
console.log(plus([1]))
Second
var arr = [1,2,3,4,5,6,7]
console.log(arr[1]) // 2
console.log(arr[[1]]) // 2
arr.splice([1],1); // removes the second item
console.log(arr)
var arr = [1,2,3,4,5,6,7]
arr.splice(1,1); // just as if you had done this
console.log(arr) // [1, 3, 4, 5, 6, 7]
The + operator doesn't work for arrays. It only works for numbers or strings.
Since javascript can't use your array with the + operator, it converts it to string before. That's why plus([1]) is "110"
You can use the push method if you want to add to an array:
array.push(newElement);
In the second example, inside splice, your array is used with an operator that doesn't support it so it is converted to a number. If you look at the MDN definition of splice, you see it expects a number, not an array.
When you want to use splice, you don't pass an array as the first argument, you pass the index of the first element to remove. If you want to remove 2 from your array, you do arr.splice(1,1);

How to determine the data type of the outcome of the spread operator in javaScript?

What is the data type of the elements outputted by spread? And is it possible to call only one element after spread, like with arrays?
Here is the example:
let ages = [1,2,3,1,4];
let chars = ['a','b','c'];
console.log(ages); // shows array> (5) [1, 2, 3, 1, 4]
console.log(...ages); // shows this> 1 2 3 1 4 - ??
console.log(typeof(ages[1]));// number
console.log(typeof(chars));// object
console.log(typeof(chars[1])); //string
//console.log(typeof(...ages)); - NOT WORKING
//console.log(typeof(...ages[1])); - NOT WORKING
Thanks!
What is the data type of the elements outputted by spread?
Each member of the array will have its own type.
And is it possible to call only one element after spread, like with arrays?
The point of a spread is to take all members of an array and spread them out.
If you want to access one member, then you shouldn't be using spread in the first place.
console.log(typeof(...ages))
This doesn't make sense. typeof tells you the type of something not many things.
Use a loop instead of a spread operator if you want to do something to each member of an array.
ages.forEach(member => { console.log(typeof member); });
console.log(typeof(...ages[1]));
Also doesn't make sense. ages[1] is the number 2. It isn't an iterable object. You can't spread it. If you want the type of that element then just:
console.log(typeof ages[1]);

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.

I am not able to understand the code

I am new to javascript. After lots of hours I am not able to understand the code. I would be grateful if someone could help me. Thanks
for(var x = 0; x < id_inters['inters'].length; x++) {
var a,b;
if(id_inters['inters'][x]['First_ID'] == data.main[0].cust) {
a = id_inters['inters'][x]['First_ID'];
b = id_inters['inters'][x]['Second_ID2'];
You can take it with these steps from the for loop:
var x is declared and assigned value of 0.
There will be an Object named id_inters which hold an array named inters which also holds objects in it.
Now inside the loop you declare two variables var a, b;.
Now that n the condition you are checking the value of the iterated object with id_inters['inters'][x]['First_Id'] where x is the index number if each iteration which is incremented from 0 to length of array.
And you are checking each iterated value to the first value of the data['main'][0].cust. Where data is an object which contains an array named data and you are comparing its first object's cust value.
You are given an array A of size N.
A partitioning of the array A is the splitting of A into one or more non-empty contiguous subarrays such that each element of A belongs to exactly one of these subarrays.
Find the number of ways to partition A such that the parity of the sum of elements within the subarrays is alternating. In other words, if Si denotes the sum of the elements in the i-th subarray, then either
S1 is odd, S2 is even, S3 is odd and so on.
or S1 is even, S2 is odd, S3 is even and so on.
For example if A=[1,2,3,3,5]. One way to partition A is [1,2][3,3][5]. Another way to partition A is [1][2][3][3,5]. Note that there exists more ways to partition this array.
Since the answer may be large, output it modulo 998244353.
Input Format
The first line contains a single integer T - the number of test cases. Then the test cases follow.
The first line of each test case contains an integer N - the size of the array A.
The second line of each test case contains N space-separated integers A1,A2,…,AN denoting the array A.
Output Format
For each test case, output the answer modulo 998244353.
Constraints
1≤T≤10000
1≤N≤2⋅105
0≤Ai≤109
Sum of N over all test cases does not exceed 2⋅105
Sample Input 1
3
3
1 2 3
4
4 4 4 4
5
1 2 3 3 5
Sample Output 1
2
1
5
Explanation
Test case 1: The array can be partitioned as follows
[1][2][3]
[1,2,3]
Test case 2: The array can be partitioned as follows
[4,4,4,4]

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);

Categories

Resources