迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 >

JS中拆分字符串并获取第一个数组元素

作者:迹忆客 最近更新:2022/12/24 浏览次数:

要拆分字符串并获取数组的第一个元素,请对字符串调用 split() 方法,将分隔符作为参数传递给它,然后访问索引 0 处的数组元素。例如,str.split(',' )[0] 在每个逗号处拆分字符串并返回第一个数组元素。

const str = 'apple,banana,melon';

const split = str.split(',');
console.log(split); // 👉️ ['apple', 'banana', 'melon']

// ✅️ get first
const first = split[0];
console.log(first); // 👉️ "apple"

// ✅️ get last
const last = split[split.length - 1];
console.log(last); // 👉️ "melon"

我们传递给 String.split 方法的唯一参数是分隔符,我们要在其上拆分字符串。

在示例中,我们在每个逗号处拆分字符串以获得子字符串数组。

const str = 'apple,banana,melon';

// 👇️ ['apple', 'banana', 'melon']
console.log(str.split(','))

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

索引在 JavaScript 中是从零开始的,这意味着数组中的第一个元素的索引为 0,最后一个元素的索引为 array.length - 1

const str = 'apple,banana,melon';

console.log(str.split(',')[0]); // 👉️ "apple"

另一种方法是使用 shift() 方法。

拆分字符串并获取第一个数组元素:

  1. 对字符串调用 split() 方法以获取子字符串数组。
  2. 在数组上调用 shift() 方法。
  3. shift() 方法移除并返回数组的第一个元素。
const str = 'apple,banana,melon';


const split = str.split(',');
console.log(split); // 👉️ ['apple', 'banana', 'melon']

// ✅️ get first
const first = split.shift();
console.log(first); // 👉️ "apple"

// ✅️ get last
const last = split.pop();
console.log(last); // 👉️ "melon"

Array.shift 方法从数组中删除第一个元素并将其返回。

该方法就地改变了原始数组,但在本例中这无关紧要,因为我们使用的是一次性数组。

使用哪种方法是个人喜好的问题。 我会继续访问索引 0 处的数组,因为我发现它更直接和直观。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

在 Pandas 中加载 JSON 文件

发布时间:2024/04/21 浏览次数:105 分类:Python

本教程介绍了我们如何使用 pandas.read_json()方法将一个 JSON 文件加载到 Pandas DataFrame 中。

将 JSON 转换为 Pandas DataFrame

发布时间:2024/04/20 浏览次数:135 分类:Python

本教程演示了如何使用 json_normalize()和 read_json()将 JSON 字符串转换为 Pandas DataFrame。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便