Array of length bracket notation - javascript

If I want to make an array that is say of length 3 using bracket notation, should I just write: var foo = [,,];
I was more used to writing: var foo = new Array(3);
I noticed that if I removed one , that my code still worked which is surprising because I am accessing all 3 elements after assigning them. How is it that it would still work?

if u do
a = []
a[3] = 100
the indices 0,1,2 will be filled in with undefined for u. u do not have to set a specific array length before using certain indices. array will grow as u use it.
all these are the same:
a = [,,,]
b = []
b.length = 3
c = new Array(3)
d = []
d[2] = undefined

Related

Setting one array equal to another array makes it behaving like an object, what am I missing? [duplicate]

This question already has answers here:
What is destructuring assignment and its uses?
(3 answers)
Closed 3 years ago.
I have set:
const [c, d ] = ["h", "i"]
in the browser console. It returns undefined.
After that, when I type c it returns "h",
and when I type d it returns "i".
To me it looks like an object where I have set the value of c and d according to ["h", "i"] 's order
I have been learning Javascript for the past 9 months. I am not sure what am I missing? Why it's behaving like this?
You are using destructuring - a great feature to directly get named access to nested properties of an Object or an Array:
const car= {
color: 'blue',
power: '120HP',
brand: 'an awesome one'
};
// Object Destructuring
const { colorOfCar, powerOfCar, brandOfCar} = car;
You are then directly able to work with each of these variable names.
It is more or less short for:
const colorOfCar = car.color;
const powerOfCar = car.power;
const brandOfCar = car.brand;
Hoping it is helpful!
Update:
An Array can be destructured the following way:
const rgb = [255, 200, 0];
// Array Destructuring
const [red, green, blue] = rgb;
Short for:
const red = rgb[0];
const green= rgb[1];
const blue= rgb[2];
You are using destructuring assignment. Then variable c = arr[0], d = arr[1]
If you need to copy array:
const newArr = arr.concat();
This statement
const [c, d ] = ["h", "i"]
is destructuring, which is not an array assignment. It doesn't read as
"an array having the elements c and d will be assigned the values of h
and i"
but it reads as
"The array having the values of h and i are destructured into
variables called c and d, respectively."
Hence, the result is not an array, nor an object, but two variables. You can use babeljs.io to check the equivalent of your code:
"use strict";
var c = "h",
d = "i";
If you are trying to set one array to equal another array all you need is:
const c = ["h", "i"];
const d = c;

How to loop/process Javascript Key:Value pairs?

Consider the following code:
a = {};
a['a'] = 1;
a['b'] = 3;
a['c'] = 5;
a['d'] = 2;
b = [];
b['a'] = 1;
b['b'] = 3;
b['c'] = 5;
b['d'] = 2;
console.log(typeof a, typeof b);
console.log(a);
console.log(b);
And the output console.log is as follow:
object object
{ a: 1, b: 3, c: 5, d: 2 }
[ a: 1, b: 3, c: 5, d: 2 ]
Granted that they are of both type object, to my understanding, a is an object of key:value pairs, where as b is an array of [key:value] pairs. Is that the right assumption?
And aside from a for(index in array) pattern of looping, where I have to use the iterator index to grab the value (array[index]), is there a better, more simple method of looping through these key/value pairs to grab the index/value or to just process the data at each index, sort of like map or reduce for arrays?
One such problem I ran into was, if I wanted to grab the key with the least count (in the above examples, it would be 'a'), is there a way to do it without using the for( index in array) pattern?
In Javascript arrays are objects, so you can add keys like you are doing in your example above, but this is not the normal way to use arrays and will probably confuse a lot of people looking at your code. There are occasional when it's useful to add a property to an array, but using them just as key stores definitely not the norm.
If you want an ordered collections with numeric indexes, use an array:
let arr = []
arr.push(10)
arr.push(20)
console.log(arr)
console.log(arr[0])
If you want properties where order isn't important and you will have string keys, use an object. In the above example you are using both types like objects — there's no reason to use an array like that.
Having said that if you want an iterator of values from an object, you can use Object.values(). This delivers an array of values from an object if you only want to process the values:
a = {};
a['a'] = 1;
a['b'] = 3;
a['c'] = 5;
a['d'] = 2;
console.log(Object.values(a))
// process them
let newArr = Object.values(a).map(n => n * 10)
console.log(newArr)
Object.entries is also useful — it returns an array of key/value pairs, which, with reduce() makes a nice way to find the minimum:
a = {
a: 1,
b: 3,
c: 5,
d: 2
};
// current will be an array of the form [key, value]
let [minKey, minValue] = Object.entries(a).reduce((min, current) => min[1] < current[1] ? min : current)
console.log(minKey, minValue)

Javascript new keyword .length not working

Hoping someone can shed some light on this simple piece of code not working as expected:
var arr = new Array(10);
arr.length; // 10. Why? Very wierd.
Why does it return 10?
You instantiated the array with ten elements
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
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
So it is impossible to create a new array with only one number element using the new keyword.
You can however do :
var arr = [10]; // Creates a new array with one element (the number 10)
console.log(arr.length); // displays 1 because the array contains one element.
I makes an Array with 10 cells... so it returns 10 :)
You wanted to do:
var arr = [10]
It returns 10, because you give only one integer, as argument, to the Array constructor. In this case, the new Array constructor is acting like some programming languages where you needed to specify the memory for your array so you don't get those ArrayIndexOutOfBounds Exceptions.
An example of this in Java:
int[] a = new int[10];
Or C#:
int[] array = new int[5];
In Javascript, when you write:
var a = new Array(10);
a[0] // returns undefined
a.length // returns 10.
and if you write:
a.toString() // returns ",,,,,,,,,", a comma for each element + 1
But, since Javascript doesn't need to allocate memory for an array, is better to use use the [] constructor:
var a = [10];
a[0] //returns 10
a.length //returns 1
I think that the thing that confuse all the people is this:
var a = new Array(1,2,3,4,5);
a[0] // returns 1
a.length // returns 5
But you can do the same in this way:
var a = [1,2,3,4,5];
a[0] // returns 1
a.length // returns 5
So, in conclusion, try to avoid using the new Array constructor, and use the [] constructor instead.

Javascript, Getting Length of String Held in Array

k = [['a'], ['ab'], ['abc']];
alert(k[2].length);
The above code fragment returns 1.
How can I get the length of the string, 3 in this case?
The object is not what is expected. Consider:
k = [['a'], ['ab'], ['abc']];
a = k[2] // -> ['abc']
a.length // -> 1 (length of array)
b = k[2][0] // -> 'abc'
b.length // -> 3 (length of string)
In your example, k is not a normal array containing strings. It contains sub-arrays, which contain the strings. You should declare k this way:
k = ['a', 'ab', 'abc'];
If you do want to use your own declaration, you could do this:
alert(k[2][0].length);​

What is the way of declaring an array in JavaScript?

I'm just learning JavaScript and it seems like there are a number of ways to declare arrays.
var myArray = new Array()
var myArray = new Array(3)
var myArray = ["apples", "bananas", "oranges"]
var myArray = [3]
What are their difference, and what are the preferred ways?
According to this website the following two lines are very different:
var badArray = new Array(10); // creates an empty Array that's sized for 10 elements
var goodArray= [10]; // creates an Array with 10 as the first element
As you can see these two lines do two very different things. If you
had wanted to add more than one item then badArray would be
initialized correctly since Javascript would then be smart enough to
know that you were initializing the array instead of stating how many
elements you wanted to add.
Is what the authors trying to say is Array(10) creates an array with precisely 10 elements and [10] creates an array of undefined size with the 0th element being 10? Or what does this mean?
In your first example, you are making a blank array, same as doing var x = []. The 2nd example makes an array of size 3 (with all elements undefined). The 3rd and 4th examples are the same, they both make arrays with those elements.
Be careful when using new Array().
var x = new Array(10); // array of size 10, all elements undefined
var y = new Array(10, 5); // array of size 2: [10, 5]
The preferred way is using the [] syntax.
var x = []; // array of size 0
var y = [10] // array of size 1: [1]
var z = []; // array of size 0
z[2] = 12; // z is now size 3: [undefined, undefined, 12]
The preferred way is to always use the literal syntax with square brackets; its behaviour is predictable for any number of items, unlike Array's. What's more, Array is not a keyword, and although it is not a realistic situation, someone could easily overwrite it:
function Array() { return []; }
alert(Array(1, 2, 3)); // An empty alert box
However, the larger issue is that of consistency. Someone refactoring code could come across this function:
function fetchValue(n) {
var arr = new Array(1, 2, 3);
return arr[n];
}
As it turns out, only fetchValue(0) is ever needed, so the programmer drops the other elements and breaks the code, because it now returns undefined:
var arr = new Array(1);
To declare it:
var myArr = ["apples", "oranges", "bananas"];
To use it:
document.write("In my shopping basket I have " + myArr[0] + ", " + myArr[1] + ", and " + myArr[2]);
There are a number of ways to create arrays.
The traditional way of declaring and initializing an array looks like this:
var a = new Array(5); // declare an array "a", of size 5
a = [0, 0, 0, 0, 0]; // initialize each of the array's elements to 0
Or...
// declare and initialize an array in a single statement
var a = new Array(0, 0, 0, 0, 0);
If you are creating an array whose main feature is it's length, rather than the value of each index, defining an array as var a=Array(length); is appropriate.
eg-
String.prototype.repeat= function(n){
n= n || 1;
return Array(n+1).join(this);
}
You can declare like this
const [alice, bob] = [1, 2]
console.log(alice) // 1
console.log(bob) // 2

Categories

Resources