标签:index 失而复得 && ninjas 收到 proxiedNinjas 数组 target
function createNegativeArrayProxy(array) {
if (!Array.isArray(array)) {
throw new TypeError("Expected an array")
} // 如果传入的参数不是数组, 则抛出异常
return new Proxy(array, { // 返回新的代理。 该代理使用传入的数组作为代理目标
get: (target, index) => { // 当读取数组元素时调用get方法
index = +index // 使用一元+操作符将属性名变成的数值
return target[index < 0 ? target.length + index : index] // 如果访问的是负向索引, 则逆向访问数组。 如果访问的是正向索引, 则正常访问数组
},
set: (target, index, val) => { // 当写入数组元素时, 调用set方法
index = +index
return target[index < 0 ? target.length + index : index] = val
}
})
}
const ninjas = ["Yoshi", "Kuma", "Hattori"] // 创建标准数组
const proxiedNinjas = createNegativeArrayProxy(ninjas) // 将数组传入create-Nigati-veArrayProx-y, 创建代理数组
if (ninjas[0] === "Yoshi" && ninjas[1] === "Kuma") {
console.log("Array items accessed through positive indexes")
}
if (proxiedNinjas[0] === "Yoshi" && proxiedNinjas[1] === "Kuma" && proxiedNinjas[2] === "Hattori") {
console.log("Array items accessed through positive indexes on a proxy")
} // 分别通过原始数组和代理数组访问数组元素
if (typeof ninjas[-1] === "undefined" && typeof ninjas[-2] === "undefined" && typeof ninjas[-3] === "undefined") {
console.log("Items cannot be accessed through negative indexes on an array")
} // 验证无法通过标准数组直接使用负向索引访问数组元素。
if (proxiedNinjas[-1] === "Hattori" && proxiedNinjas[-2] === "Kuma" && proxiedNinjas[-3] === "Yoshi") {
console.log("But they can be accessed through negative indexes")
} // 但是可以通过代理使用负向索引访问数组元素, 因为代理get方法进行了必要的处理
proxiedNinjas[-1] = "Hachi"
if (proxiedNinjas[-1] === "Hachi" && ninjas[2] === "Hachi") {
console.log("Items can be changed through negative indexes")
} // 通过代理, 我们也可以通过负向索引设置数组元素
标签:index,失而复得,&&,ninjas,收到,proxiedNinjas,数组,target 来源: https://www.cnblogs.com/lvhanghmm/p/15343005.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。