在 TypeScript 中获取数组的最后一个元素
使用 Array.at() 方法获取 TypeScript 中数组的最后一个元素,例如 const last = arr.at(-1)。 当传递一个负索引时,at() 方法通过从数组末尾倒数返回一个元素。
const arr: string[] = ['a', 'b', 'c'];
// ?️ const lastAgain: string | undefined
const last = arr.at(-1);
console.log(last); // ?️ "c"
if (last !== undefined) {
console.log(last.toUpperCase()); // ?️ "C"
}
// ?️ Or use optional chaining
console.log(last?.toUpperCase()); // ?️ "C"
我们使用 Array.at() 方法来获取 TypeScript 中数组的最后一个元素。
该方法采用的唯一参数是要返回的数组元素的索引。
at() 方法返回数组中与提供的索引匹配的元素,如果找不到给定的索引,则返回 undefined。
这是准确的,因为如果数组为空,则返回值将是 undefined。
const arr: string[] = [];
// ?️ const lastAgain: string | undefined
const last = arr.at(-1);
console.log(last); // ?️ undefined
if (last !== undefined) {
console.log(last.toUpperCase());
}
// ?️ Or use optional chaining
console.log(last?.toUpperCase()); // ?️ undefined
我们可以通过使用简单的类型保护来绕过可能未定义的值。
if 语句和可选的链接 ?. 运算符用作类型保护并排除值未定义的可能性,这使我们能够使用特定于类型的内置方法。
或者,我们可以访问最后一个索引处的数组元素。
要在 TypeScript 中获取数组的最后一个元素,请访问索引为 array.length – 1 的数组,例如 const last = arr[arr.length – 1]。 计算结果为数组中最后一个元素的索引。
const arr: string[] = ['a', 'b', 'c'];
// ?️ const last: string
const last = arr[arr.length - 1];
console.log(last); // ?️ "c"
if (last !== undefined) {
console.log(last.toUpperCase());
}
console.log(last?.toUpperCase());
const arr: string[] = [];
// ?️ const last: string
const last = arr[arr.length - 1];
console.log(last); // ?️ undefined
即使数组为空,最后一个变量在 TypeScript 中被键入为字符串。
这可能不是我们想要的,因为如果访问一个属性或对一个未定义的值调用一个方法,我们会得到一个错误。
const arr: string[] = [];
// ?️ const last: string
const last = arr[arr.length - 1];
console.log(last); // ?️ undefined
// ⛔️ Cannot read properties of undefined (reading 'toUpperCase')
console.log(last.toUpperCase());
我们可以使用类型保护来解决这个问题。
const arr: string[] = [];
// ?️ const last: string
const last = arr[arr.length - 1];
if (last !== undefined) {
console.log(last.toUpperCase());
}
// ?️ Or use optional chaining
console.log(last?.toUpperCase()); // ?️ undefined
我们可以确定最后一个变量在 if 块中存储了一个字符串。
或者,我们可以使用可选的链接 ?. 运算符,如果引用未定义或为空,它会短路而不是抛出错误。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。