如果最后一个元素在javascript中未定义,则array.length返回undefined。 [英] array.length returns undefined if the last element is undefined in javascript

查看:86
本文介绍了如果最后一个元素在javascript中未定义,则array.length返回undefined。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

function lastElement(array) {
  if (array.length > 0)
    return array[array.length - 1];
  else
    return undefined;
}

alert(lastElement([ undefined,1, 2]));

由于不计算未定义元素&现在,如果我用未定义的值交换数组中的最后一个元素:

Which returns 2 since it doesn't counts the undefined element & that's perfectly fine.Now if i swap the last element in the array with the undefined:

function lastElement(array) {
  if (array.length > 0)
    return array[array.length - 1];
  else
    return undefined;
}

alert(lastElement([ 1, 2,undefined]));

返回未定义!为什么会这样呢?感谢所有帮助。

It returns undefined!! Why is it so? Any help appreciated.

推荐答案

因为数组中的最后一个元素是 undefined

Because the last element in the array is undefined.

该数组具有3个元素,分别为 1 2 undefined ,其中undefined的索引为2,数组的长度为3。

The array has 3 elements 1, 2 and undefined where undefined has the index 2 and the array has a length of 3.

因此,当 array [array.length-1] 返回它是 undefined

这篇关于如果最后一个元素在javascript中未定义,则array.length返回undefined。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆