“什么是更好的写作方式?”;array.length-1“;用JavaScript?

“什么是更好的写作方式?”;array.length-1“;用JavaScript?,javascript,arrays,prototype,Javascript,Arrays,Prototype,与使用array.length-1获取数组的最大索引不同,您可以执行类似于array.largestIndex的操作吗?您可以使用JS getter来执行此操作 Object.defineProperty(Array.prototype, 'largestIndex', { get: function () { return (this.length == 0) ? null : this.length - 1 } });

与使用
array.length-1
获取数组的最大索引不同,您可以执行类似于
array.largestIndex
的操作吗?

您可以使用JS getter来执行此操作

Object.defineProperty(Array.prototype, 'largestIndex', {
   get: function () {
      return (this.length == 0) ? null : this.length - 1
   }
});