Jump to content

JavaScript/Arrays/Exercises

From Wikibooks, open books for an open world

Topic: Arrays

1. What is the output of the following script?

"use strict";constx=[];x[1]=5;console.log(x);x[2]=[,,42];console.log(x);
Click to see solution
[undefined, 5][undefined, 5, [undefined, undefined, 42]]



2. Add elements

  • Create an array with all odd numbers that are smaller than 10.
  • Show the array with the alert command.
  • Show how many elements the array contains.
  • Add 2, 4, 6, 8 to the end of the array and show it again.
  • Insert the value 20 on the 20th array element and show the array again.
Click to see solution
"use strict";// literal notationconstarr=[1,3,5,7,9];alert(arr);// or: console.log(arr);alert("The array contains "+arr.length+" elements.");// add elementsarr.push(2,4,6,8);alert(arr);// one certain elementarr[19]=20;// 19!alert(arr);alert("The array now contains "+arr.length+" elements.");



3. Remove elements

  • Create an array with all numbers from 1 to 6.
  • Show the array with the alert command.
  • Delete the first and last element and show the resulting array.
Click to see solution
"use strict";constarr=[1,2,3,4,5,6];alert(arr);// or: console.log(arr);// remove elementsconstfirst=arr.shift();alert("Removed the first element: "+first);alert(arr);constlast=arr.pop();alert("Removed the last element: "+last);alert(arr);



4. Combine elements

  • Create an empty array.
  • Add 0, 1, 2 to the array with the push method and show the array.
  • Create the string "0 + 1 + 2" out of the array using the join method and show the string.
Click to see solution
"use strict";constarr=[];arr.push(0);arr.push(1);arr.push(2);alert(arr);conststr=arr.join(" + ");alert(str);
close