js array.at All In One
const arr = [1, 3, 5];
const index = 2;
console.log('arr[index] =', arr[index]);
// arr[index] = 5
console.log('arr.at(index) =', arr.at(index));
// arr.at(index) = 5
demo
const colors = ['red', 'green', 'blue'];
// 1. 使用 indexOf
const indexTarget = colors[colors.indexOf('green')];
console.log('indexTarget =', indexTarget);
// 'green'
// 2. 使用 length 计算
const lenTarget = colors[colors.length - 2];
console.log('lenTarget =', lenTarget);
// 'green'
// 3. 使用 slice
const sliceTarget = colors.slice(-2, -1);
console.log('sliceTarget =', sliceTarget[0]);
// 'green'
// 4. 使用 at
const atTarget = colors.at(-2);
console.log('atTarget =', atTarget);
// 'green'
// 5. 使用 index
const target = colors[-2]
console.log('target =', target);
// 'green'
Array.at
https://caniuse.com/?search=Array.at
https://caniuse.com/mdn-javascript_builtins_array_at
refs
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 ️,侵权必究⚠️!