获取字符串最后一个字符有几种常用方法:
1. 使用 charAt() 和 length
const str = "Hello World";
const lastChar = str.charAt(str.length - 1);
console.log(lastChar); // 输出 "d"
2. 使用数组索引方式
const str = "Hello World";
const lastChar = str[str.length - 1];
console.log(lastChar); // 输出 "d"
3. 使用 slice() 方法
const str = "Hello World";
const lastChar = str.slice(-1);
console.log(lastChar); // 输出 "d"
4. 使用 substr() 方法(注意:此方法已废弃,不推荐)
const str = "Hello World";
const lastChar = str.substr(-1);
console.log(lastChar); // 输出 "d"
注意事项
-
空字符串处理:
const str = ""; const lastChar = str.length > 0 ? str.slice(-1) : ""; -
包含Unicode字符(如emoji)时:
const str = "Hello😊"; const lastChar = [...str].pop(); // 正确获取"😊" -
性能考虑:
- 对于长字符串,
str[str.length - 1]性能最好 slice(-1)代码最简洁
- 对于长字符串,
选择哪种方法取决于具体场景,大多数情况下 slice(-1) 是最简洁明了的选择。