在 React.js 中获取数组的第一个元素

在 React 中使用方括号获取数组的第一个元素,例如 const first = arr[0];. 索引为 0 的数组元素是数组中的第一个元素。 如果数组为空,则返回 undefined 值。

import {useState} from 'react';

const App = () => {
  const [state, setState] = useState([
    {id: 1, name: 'Alice'},
    {id: 2, name: 'Bob'},
  ]);

  const first = state[0];

  return (
    <div>
      <h2>id: {first?.id}</h2>
      <h2>name: {first?.name}</h2>
    </div>
  );
};

export default App;

我们访问索引 0 处的元素以获取数组的第一个元素。

JavaScript 中的索引从零开始,因此数组中的第一个元素的索引为 0,最后一个元素的索引为 arr.length – 1。

请注意 ,在访问索引为 0 的数组元素的属性时,我们使用了可选链 ?. 运算符。

如果引用为空(null 或 undefined),则可选链接 ?. 运算符会短路。

换句话说,如果第一个变量存储了一个未定义的值,我们将短路而不是尝试访问未定义值的属性并获得运行时错误。

我们也可以使用 if 语句。

import {useState} from 'react';

const App = () => {
  const [state, setState] = useState([
    {id: 1, name: 'Alice'},
    {id: 2, name: 'Bob'},
  ]);

  const first = state[0];

  // 👇️ Make sure first is not undefined
  if (first != undefined) {
    console.log(first.id);
    console.log(first.name);
  }

  return (
    <div>
      <h2>id: {first?.id}</h2>
      <h2>name: {first?.name}</h2>
    </div>
  );
};

export default App;

除非我们确定数组不为空,否则这是必要的。

如果我们尝试在不存在的索引处访问数组,我们将得到一个未定义的值。

const arr = [];

console.log(arr[0]); // 👉️ undefined

如果我们尝试访问属性或调用 undefined 值的方法,则会收到运行时错误。