Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

javascript array negative index

const arr = ["first", "second", "third"]
console.log(arr[-1]) // Will return undefined
Comment

negative index javascript

// Usually negative indexes do not work

const array = [ 1, 2, 3 ];
const string = "123";

console.log(array[-1]); // -> undefined
console.log(string[-1]); // -> undefined

// However arrays and strings have an `at` property which allows negative indexes
// a negative index will work from the end of the array/string backwards:
Indexes: 0  1  2
Array: [ 1, 2, 3 ]
Indexes:-3 -2 -1

/* Array/String.prototype.at essentially acts like this:
Array.prototype.at = String.prototype.at = function(index) {
	if (index < 0) {
		index = -index;
		while (index >= this.length) {
			index -= this.length;
		}
		if (index === 0) {
			return this[0];
		}
		return this[this.length - index];
	} else {
		while (index >= this.length) {
			index -= this.length;
		}
		return this[index];
	}
};
*/

console.log(array.at(-1)); // -> 3
console.log(string.at(-1)); // -> 3
Comment

PREVIOUS NEXT
Code Example
Javascript :: check if content is overflowing react 
Javascript :: React Router rendering blank pages for all components 
Javascript :: javascript Why is this function working on second click only 
Javascript :: Javascript shows me TypeError saying my variable is undefined 
Javascript :: js remove child with index 
Javascript :: -1 in js 
Javascript :: how to use same component in multiple place with some logic in angularjs 
Javascript :: Display name instead ID modal dropdown in angularjs 
Javascript :: Delete Button not working with json server using angularjs 
Javascript :: Angularjs $on called twice 
Javascript :: AngularJS Pagination not showing all pages 
Javascript :: AngularJS Form validation transition to valid when some elements are not even touched yet 
Javascript :: Changing Component File location in React native does not show in main App 
Javascript :: how to edit data retrieval using jsp 
Javascript :: async mutex 
Javascript :: JSON.stringify on Arrays adding numeric keys for each array value 
Javascript :: socket.io authentication 
Javascript :: get copied text javascript 
Javascript :: react native push notifications cancel delivered notification 
Javascript :: slow down an action or event 
Javascript :: javascript looping through array 
Javascript :: Jquery JavaScript Prevent From Press Enter Key Keyboard 
Javascript :: Javascript Encapsulation Inheritance Polymorphism Composition 
Javascript :: javascript reverse string short hand 
Javascript :: NodeJS Database initialisation 
Javascript :: unhide is not working with radio button javascript 
Javascript :: prisma graphql n+1 problem solution 
Javascript :: fs.writefile example in aws lambda 
Javascript :: Backbone Model And Collection 
Javascript :: Using Fetched Data With Backbone 
ADD CONTENT
Topic
Content
Source link
Name
7+7 =