最近发现es13中at()方法比较实用,故分享下实用心得:
at() 是一个数组方法,用于通过给定索引来获取数组元素。
当给定索引为正数时,这种新方法与使用中括号表示法访问具有相同的行为;
当给出负整数索引时,就会从数组的最后一项开始检索;(较实用)
数组使用:
const arr = [1,2,3,4,5,6];
console.log(arr[1]); // 2
console.log(arr.at(1)); // 2
console.log(arr[arr.length - 1]); // 6
console.log(arr.at(-1)); // 6
console.log(arr[arr.length - 2]); //5
console.log(arr.at(-2)); //5
字符串也可使用:
const str = "csdn";
console.log(str[str.length - 1]); // n
console.log(str.at(-1)); // n
总结:相对来说使用ES13中at()方法用来获取数组或字符串最后一项时变得更加方便简洁,如有不对请批评指正!