You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在函数中返回数组的第一个元素?

如何在函数中返回数组的第一个元素?

不管使用哪种编程语言,获取数组第一个元素的核心逻辑都是利用数组的零起始索引特性(即第一个元素的索引为0)。以下是几种主流语言的实现示例:

JavaScript 实现

直接通过索引[0]访问数组第一个元素,同时可添加空数组处理逻辑避免异常:

基础实现

function getFirstValue(arr) {
  return arr[0];
}

// 测试示例
console.log(getFirstValue([1, 2, 3])); // 输出: 1
console.log(getFirstValue([80, 5, 100])); // 输出: 80

含空数组处理的实现

function getFirstValue(arr) {
  // 数组为空时返回null,也可替换为其他默认值
  return arr.length > 0 ? arr[0] : null;
}

Python 实现

Python列表同样支持零起始索引,直接通过[0]获取第一个元素:

基础实现

def get_first_value(arr):
    return arr[0]

# 测试示例
print(get_first_value([1, 2, 3])) # 输出: 1
print(get_first_value([80, 5, 100])) # 输出: 80

含空列表处理的实现

def get_first_value(arr):
    # 列表为空时返回None,或自定义默认值
    return arr[0] if arr else None

Java 实现

Java数组需注意非空判断,避免NullPointerException或数组越界:

实现代码

public class ArrayUtils {
    public static int getFirstValue(int[] arr) {
        if (arr == null || arr.length == 0) {
            throw new IllegalArgumentException("数组不能为空或长度为0");
        }
        return arr[0];
    }

    public static void main(String[] args) {
        System.out.println(getFirstValue(new int[]{1, 2, 3})); // 输出: 1
        System.out.println(getFirstValue(new int[]{80, 5, 100})); // 输出: 80
    }
}

核心要点

  • 绝大多数编程语言的数组/列表都采用零起始索引,第一个元素的索引固定为0;
  • 实际开发中建议添加边界判断(如空数组、null数组),避免运行时异常或返回非预期值。

内容的提问来源于stack exchange,提问作者Kunal Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 19:05:23