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 :: use recoil oitside 
Python :: ignore filter warnings jupyter notebook 
Python :: All caps alphabet as list 
Python :: epa meaning 
Python :: ignore warnings python 
Python :: francais a anglais 
Python :: suppres tensorflow warnings 
Python :: drop the last row of a dataframe 
Python :: pandas save file to pickle 
Python :: python - show all columns / rows of a Pandas Dataframe 
Python :: transform size of picture pygame 
Python :: drop a range of rows pandas 
Python :: change django admin title 
Python :: drop a column pandas 
Python :: remove all pycache files 
Python :: download files from google colab 
Python :: sleep 5 seconds py 
Python :: combine path python 
Python :: How to play music without pygame 
Python :: how to print a list without brackets and commas python 
Python :: meter to cm in python 
Python :: request url in web scraping 
Python :: txt to list python 
Python :: convert numpy to torch 
Python :: python delete saved image 
Python :: python get full path 
Python :: how to sort by length python 
Python :: erode dilate opencv python 
Python :: days of week 
Python :: jupyter clear cell output programmatically 
ADD CONTENT
Topic
Content
Source link
Name
9+7 =