gpt4 book ai didi

javascript - 是否可以在数组中使用 Getter/Setter?

转载 作者:行者123 更新时间:2023-12-04 01:43:06 25 4
gpt4 key购买 nike

我刚刚了解了对象的 Getters/Setter 并决定使用它。但是,我试图将 Getter 放入数组中,但没有成功。这是不可能的还是我只是做错了什么?

const obj = {
a: 1,
get b() { return this.a + 1 }
}

console.log(obj.b) //2

对于数组

const arr = [
1,
get () { return this[0] + 1 }
]

console.log(arr[1]) // Doesn't work

最佳答案

Is it not possible or am I just doing something wrong?

不可能使用数组初始值设定项(松散地称为“数组文字”)。

不过,您可以在事后通过 Object.defineProperty 定义访问器属性。 :

const arr = [1];
Object.defineProperty(arr, "1", {
get() {
return this[0] + 1;
}
});

console.log(arr[1]); // 2

您可以将其结合起来,为了清楚起见,我将上述步骤分开,但是 Object.defineProperty返回你调用它的对象,所以:

const arr = Object.defineProperty([1], "1", {
get() {
return this[0] + 1;
}
});

console.log(arr[1]); // 2

我不会,但你可以。 :-) 我为什么不呢?因为数组期望其具有数组索引名称的属性是简单的数据属性,而不是访问器,所以如果尝试设置 splice,各种数组方法(如 "1")将失败。属性设置为不同的值(您可以通过添加 setter 来修复该问题)。不过,一般来说,我会单独保留数组条目属性。

就是说,如果该属性同时具有 getter 和 setter,我立即不能认为它有问题。这是上面的 setter ,只是为了完整性:

const arr = Object.defineProperty([1], "1", {
get() {
return this[0] + 1;
},
set(value) {
this[0] = value - 1;
}
});

console.log(arr); // [1, 2]
arr[1] = 42;
console.log(arr); // [41, 42]
arr[0] = 27;
console.log(arr); // [27, 28]
.as-console-wrapper {
max-height: 100% !important;
}


¹“数组索引名称”- 这就是 the spec says关于作为数组索引的属性名称:

An integer index is a String-valued property key that is a canonical numeric String (see 7.1.16) and whose numeric value is either +0 or a positive integer ≤ 253 - 1. An array index is an integer index whose numeric value i is in the range +0 ≤ i < 232 - 1.

关于javascript - 是否可以在数组中使用 Getter/Setter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53976882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com