In JavaScript, arrays store a list of items. An item may be a primitive such as a string or number. An item may also be an object or another array. Indexing starts at 0.
Arrays are objects. To determine if a variable is an array, use
Object.prototype.toString.call(theArray) === '[object Array]'
or the newer way of
Array.isArray(theArray);
Some of the more commonly used actions that may be performed on an array include:
Initialize:
let myArray = ['a', 'b', 'c'];
Arrays can be created by calling:
let myArray2 = new Array('a', 'b', 'c');
The first way is much simpler, so there's not really any reason to use this way.
To retrieve the number of items in the list, do the following:
let count = myArray.length;
Individual items in an array may be accessed by it's index. To access the first item, call
let firstItem = myArray[0];
To access the last item, call
let lastItem = myArray[myArray.length-1];
Add an item to the end of the list:
myArray.push('d');
Add an item to the beginning of the list:
myArray.unshift('d');
Remove last item:
myArray.pop();
Remove first item:
myArray.shift();
Get the number of items in an array:
let count = myArray.length();
Get the index of an item in an array: Note: this returns -1 if the item is not found:
let index = myArray.indexOf('b');
Return a certain range of items, based on index, from an array:
let subset = myArray.slice(1, 2);
I tend to use objects more than arrays, but one common way to use arrays is when extracting pieces of a string. A string, such as an id, may contain several pieces of information separated by a delimiter. For example, the following string could represent a date with a dash as the delimiter:
01-20-2020
The month, date and year could be extracted as follows:
let dateStr = '01-20-2020';
let datePieces = dateStr.split('-');
console.log('Month: ' + datePieces[0]);
console.log('Day: ' + datePieces[1]);
console.log('Year: ' + datePieces[2]);
An array may store another array, creating a multidimensional array. For example:
let array2d = [[0,0], [3,5]];
Arrays can be searched using the Array.prototype.find function. A callback function which defines the search criteria is passed into the find function. The result is then returned.
Example:
function search (item) {
return item === 'b';
}
let bElement = myArray.find(search);
Implementation:
Inside the javascript_tutorial.js file created in the JavaScript set up tutorial, add the following lines that are in bold:
// JavaScript Tutorial /* * This file will add JavaScript * to a website. */ (function() { let doc = document; let defaultLocation = [-86.7816, 36.1627]; // longitude, latitude })();
The JavaScript tutorial series starts with this post.
(paid links)
More JavaScript
Comments
Post a Comment