
您可以在 hub 仓库中找到这篇文章中的所有代码。
代理相关的挑战
访问负索引
/**
* @param {Array} arr
*/
function withNegativeIndex(arr) {
return new Proxy(arr, {
get(target, property, receiver) {
const index = Number(property);
if (index < 0) {
property = target.length + index;
}
return Reflect.get(target, property, receiver);
}
});
}
// Usage example
const fruits = ["apple", "banana", "orange"];
const proxiedFruits = withNegativeIndex(fruits);
console.log(proxiedFruits[-1]); // => 'orange'
console.log(proxiedFruits[-2]); // => 'banana'
console.log(proxiedFruits[-3]); // => 'apple'
console.log(proxiedFruits[0]); // => 'apple'
console.log(proxiedFruits[1]); // => 'banana'
console.log(proxiedFruits[2]); // => 'orange'
登录后复制
参考
- 代理 – mdn
以上就是代理 – JavaScript 挑战的详细内容,更多请关注米云其它相关文章!
