Mid Term study Arrays Flashcards
Three ways to declare an Array?
let numbers = Array();
// OR
let numbers = new Array();
// OR
let numbers = [];
How to create an empty array with 3 elements
let numbers = Array(3);
How to add the number 10 to the Array below?
let numbers = [2, 4, 6, 8];
numbers[4] = 10;
What is output to the console from below:
let numbers = [2, 4, 6, 8];
console.log(numbers);
(4) [2, 4, 6 ,8]
(4) -> this is the array length
[2, 4, 6, 8] -> these are the array elements
What is the output to the console from below:
let numbers = [2, 4, 6, 8];
numbers.length = 2;
console.log(numbers.length);
console.log(numbers);
console.log(numbers.length);
outputs: 2
console.log(numbers);
outputs: [2, 4]
Is the below possible?:
let things = [24, “cat”, 8.9, true];
console.log(things);
Yes because Javascript can hold any data type
How to return index[2] from this array?
let numbers = [2, 4, 6, 8];
numbers.at(2)
.at() method will return the value at the specified index.
What is the console output:
let numbers = [2, 4, 6, 8];
console.log(numbers.at(-2))
output would be 6
Why are the .push() and .pop() array methods faster than the .shift() and .unshift() methods?
.pop() and .push() are faster than .shift()/.unshift() because .shift/unshift require you to re-index every other array element. While pop and push just remove or add to the end of the array.
What happens below:
let numbers = [2, 4, 6, 8];
console.log(numbers.pop()):
numbers.push(5);
console.log(numbers.pop()): - > pops the last element from the array(8 in this case)
numbers.push(5); - > pushes 5 to the end of the array
What happens below:
let numbers = [2, 4, 6, 8];
console.log(numbers.shift()):
numbers.unshift(5);
console.log(numbers.shift()): ->shifts the first element from the array(2 in this case)
numbers.unshift(5); - > shifts 5 to the start of the array
How do you Join the arrays below?
let numbers = [2, 4, 6, 8];
let more = [1, 2, 3];
numbers = numbers.concat(more);
Array is now:
[2, 4, 6, 8, 1, 2, 3]
How would you join all the elements in the array below into a string with each element spaced by “:”
let numbers = [2, 4, 6, 8];
let new = numbers.join(“:”):
new would equal the string
“2:4:6:8”
How would you copy part of an array, and copy from indexes 4, 5, 6 from the array below:
let numbers = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20];
let new = numbers.slice(4, 7);
.slice(start, end)
.slice is inclusive of the start but exclusive of the end.
Explain what the Array.splice() below does?
let numbers = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20];
let new = numbers.splice(4, 5);
Array.splice(start index, how much elements);
will start at index 4(value 10) and take from 5 indexes from there(inclusive). So new will equal [10, 12, 14, 16, 18]