0

例如(在 JavaScript 中):

//Not that I would ever add a method to a base JavaScript prototype... 
//(*wink nudge*)...
Array.prototype.lastIndex = function() {          
  return this.length - 1;
}

console.log(array[array.lastIndex()]);

对比

console.log(array[array.length - 1]);

从技术上讲,后一种方法少用了一个字符,但也使用了一个幻数。当然,在这种情况下,可读性可能不会真正受到影响,但幻数很糟糕。使用哪个更好的做法?

4

4 回答 4

6

我认为在许多情况下10不能真正算作“神奇数字”。当您指的是最后一项的索引(即length - 1)时,那肯定是我不会考虑1幻数的时候。

于 2012-08-01T21:28:56.037 回答
1

不同的语言有自己惯用的方式来访问数组的最后一个元素,应该使用这种方式。例如,在 Groovy 中,这将是:

myArray.last()

在 C 语言中,很可能会这样做:

my_array[len - 1]

在 Common Lisp 中,类似:

(first (last my_list))
于 2012-08-01T21:34:08.787 回答
1

我同意@DragonWraith 的观点,即 1 不是幻数。然而,这不是关于幻数,而是关于可读性。如果你需要最后一个索引使用myArray.lastIndex(),如果你需要最后一个元素使用myArray.last()myArray.lastElement()。它比阅读和理解更容易myArray[myArray.length - 1]

于 2012-08-02T06:47:03.633 回答
0

My take is that we should be looking for the style which the most programmers will be familiar with. Given that anyone who's been programming for more than a couple weeks in a language with this sort of array syntax (i.e., C-influenced imperative languages) will be comfortable with the idea that arrays use 0-based indexing, I suspect that anyone reading your code will understand what array[array.length-1] means.

The method calls are a bit less standard, and are language-specific, so you'll spend a bit more time understanding that if you're not totally familiar with the language. This alone makes me prefer the length-1 style.

于 2012-08-01T21:37:32.810 回答