“Negativer Index JavaScript” Code-Antworten

Negativer 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
MattDESTROYER

JavaScript Array Negativer Index

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

Ähnliche Antworten wie “Negativer Index JavaScript”

Fragen ähnlich wie “Negativer Index JavaScript”

Weitere verwandte Antworten zu “Negativer Index JavaScript” auf JavaScript

Durchsuchen Sie beliebte Code-Antworten nach Sprache

Durchsuchen Sie andere Codesprachen