提问人:user19809568 提问时间:10/26/2022 最后编辑:Mister Jojouser19809568 更新时间:10/26/2022 访问量:262
是否可以隐藏属性?
Is it possible to hide properties?
问:
我正在尝试在 JS 中重新创建一个 Set 对象,我已经弄清楚了。我只是想知道是否可以隐藏对象的属性。我不认为有,所以我想问。
这就是问题所在:
/* 声明一个函数 'Collection',该函数将数组作为参数,并在使用 'new' 关键字调用时返回 'Collection' 对象的实例。 “Collection”对象的功能应该类似于 Set - 即,它们将在其值和键相同的位置存储 UNIQUE 值(无重复项)。 所有 Collection 对象都应包含自己的“size”属性,该属性跟踪它们包含的项数。首次创建集合时,它的大小应为 0。 */
这是我最初所拥有的:
function Collection (arr) {
// size property initialized to 0
this.size = 0;
// cache property to store unique arr elements
this.cache = {}
// loop thru input arr
for (let i = 0; i < arr.length; i++) {
// if the current arr element is not a key in the cache prop, create a key/val pair
if (!this.cache[arr[i]]) {
// key and value are the same
this.cache[arr[i]] = arr[i];
// increment the size prop
this.size ++;
};
};
}
const testObj = new Collection([1, 2, 2, 3, true, true, 'hi', 'hi'])
console.log(testObj.cache); // {'1': 1, '2': 2, '3': 3, 'true': true, 'hi': 'hi'}
console.log(testObj.size); // -> 5
我创建了一个对象作为属性,因为我希望能够在没有 size 属性的情况下将对象记录到控制台。但我认为最好不要将对象声明为属性。
这让我想到了我的第二个解决方案。但是当我控制台记录它时,这显示了 size 属性。
function Collection (arr) {
// size property initialized to 0
this.size = 0;
// loop thru input arr
for (let i = 0; i < arr.length; i++) {
// if the current arr element is not a key in the cache prop, create a key/val pair
if (!this[arr[i]]) {
// key and value are the same
this[arr[i]] = arr[i];
// increment the size prop
this.size ++;
};
};
}
// const testObj = new Collection([1, 2, 2, 3, true, true, 'hi', 'hi'])
// console.log(testObj); // {'1': 1, '2': 2, '3': 3, size: 5, 'true': true, 'hi': 'hi'}
// console.log(testObj.size); // -> 5
答:
0赞
Jacob Malland
10/26/2022
#1
您可以创建自己的自定义 Collection 类,而不是创建以相同方式操作的函数。
class Collection {
cache = []
size = 0
constructor(list) {
this.addAll(list)
}
contains(item) {
return(this.cache.includes(item))
}
add(item) { // Add single item
if (!this.contains(item)) { // Check for duplicates
this.cache.push(item) // Add item
this.size ++ // Increment size
return(true) // Return true if added
}
return(false) // Return false if already exists
}
addAll(list) {
for (element of list) { // Loop through each element
this.add(element) // Use the singular add method to add the item
}
}
}
拥有类和所需的任何方法后,只需创建新的 Collection 对象并输出缓存:
test = new Collection([1, 2, 3, 4, 5])
console.log(test.cache)
如果您不想拥有 ,则可以改用自己的方法,但您仍然必须输出。test.cache
toString
test.toString()
如果您希望能够运行并且没有打印尺寸,那么您就不走运了。console.log(test)
评论
0赞
user19809568
10/26/2022
啊,好吧,这就是我的想法,感谢您对创建类的见解
评论
But this shows the size property when I console log it
与第一个代码一样Collection
this.#propertyname