Javascript 为什么我需要.length来找到for循环中数组元素的等价性?

Javascript 为什么我需要.length来找到for循环中数组元素的等价性?,javascript,arrays,if-statement,indexing,Javascript,Arrays,If Statement,Indexing,我正在处理的问题会在数组上迭代,但根据我在数组中的位置,有三种不同的行为: 1.最后一个要素:做一件事; 2.倒数第二个元素:do B; 3.所有其他元素:do C 为了确定我的立场,我使用了if语句,并注意到当我只使用[-1]和[-2]的索引时,if语句的计算结果并不像预期的那样。为什么? for(let i = 0; i < arr.length; i++){ if (arr[i] === arr[arr.length-1]){console.log(`last itme`)} /

我正在处理的问题会在数组上迭代,但根据我在数组中的位置,有三种不同的行为: 1.最后一个要素:做一件事; 2.倒数第二个元素:do B; 3.所有其他元素:do C

为了确定我的立场,我使用了if语句,并注意到当我只使用[-1]和[-2]的索引时,if语句的计算结果并不像预期的那样。为什么?

for(let i = 0; i < arr.length; i++){
  if (arr[i] === arr[arr.length-1]){console.log(`last itme`)} // This one evaluates i to be equal to the last item in the array when i is length-1
  if (arr[i] === arr[-1]){console.log(`last itme`)} // This one *does not* evaluates i to be equal to the last item in the array when i is length-1
}
for(设i=0;i

抱歉,如果这是重复的-我做了搜索,找不到任何类似的。谢谢

因为数组索引从0开始。像-1或-2这样的值在JS中不是可用的索引


(也许你有pythonic的背景,因为它在python中意味着什么。)

JS中的数组索引定义为

字符串属性名
p
是数组索引,当且仅当
ToString(ToUint32(p))
等于
p
ToUint32(p)
不等于
2^32-1

(实际上,它表示
[0;2^32-1)
范围内的整数)

因此,像
-1
这样的负索引虽然可能有用,但并不存在

参考资料:


实际上,将if语句移出循环是有意义的,因为在当前代码中,数组会出现一些有趣的行为,如:

 [1, 1, 1, 1]
因为它将始终输入两个ifs。因此,您可以执行以下操作:

 if(arr.length > 0) {
   const last = arr[arr.length - 1];
   //...
 }

 if(arr.length > 1) {
  const second = arr[arr.length - 2];
  //...
 }

 for(const rest of arr.slice(0, -2)) {
   //...
 }

因为
-1
不是一个有效的数组索引。数组是一个项目列表,比如说
[1,2,3]
;哪一个是“负第一”?谢谢Arash!说我有“背景”让我感觉很大方,因为我对编程一般来说是多么的陌生,但我确实是从Python开始的-所以也许这就是我学会它的地方!