“indeks negatif JavaScript” Kode Jawaban

indeks negatif 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

indeks negatif array javascript

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

Jawaban yang mirip dengan “indeks negatif JavaScript”

Pertanyaan yang mirip dengan “indeks negatif JavaScript”

Lebih banyak jawaban terkait untuk “indeks negatif JavaScript” di JavaScript

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya