-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathProxy_5.html
More file actions
30 lines (28 loc) · 807 Bytes
/
Proxy_5.html
File metadata and controls
30 lines (28 loc) · 807 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
//下面的例子使用get拦截,实现数组读取负数的索引。
function createArray(...elements) {
let handler = {
get(target, propKey, receiver) {
let index = Number(propKey);
if (index < 0) {
propKey = String(target.length + index);
}
return Reflect.get(target, propKey, receiver);
}
};
let target = [];
target.push(...elements);
return new Proxy(target, handler);
}
let arr = createArray('a', 'b', 'c');
arr[-1] // c
</script>
</body>
</html>