Skip to content

Instantly share code, notes, and snippets.

@Aleksey-Danchin
Created October 12, 2016 07:36
Show Gist options
  • Save Aleksey-Danchin/392238502acd01ec9e83511b1b817f95 to your computer and use it in GitHub Desktop.
Save Aleksey-Danchin/392238502acd01ec9e83511b1b817f95 to your computer and use it in GitHub Desktop.
Доступ к первому элементу массива через .first / Доступ к последнему элементу массива через .last
Object.defineProperty(Array.prototype, 'first', {
enumerable: false
, configurable: true
, get: function () { return this[0]; }
, set: function (value) {
return this.length ? this[0] = value : this.push(value) && value;
}
});
Object.defineProperty(Array.prototype, 'last', {
enumerable: false
, configurable: true
, get: function () { return this[this.length - 1]; }
, set: function (value) {
return this.length ? this[this.length - 1] = value : this.push(value) && value;
}
});
const array = ['a', 'b', 'c', 'd'];
console.log(array.first, array[0]); // a, a
console.log(array.last, array[array.length - 1]); // b, b
array[0] = 'foo';
array[3] = 'bar';
console.log(array.first, array[0]); // 'foo', 'foo'
console.log(array.last, array[array.length - 1]); // 'bar', 'bar'
array.first = 100;
array.last = 150;
console.log(array.first, array[0]); // 100, 100
console.log(array.last, array[array.length - 1]); // 150, 150
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment