我正在尝试使用我在该“obj”中定义的属性来填充对象“obj”内的数组“arr” ',在本例中为属性 'x';
基本上,数组将有 x 值,但相反,当访问“arr”时,所有条目都是未定义。
我做了什么:
var obj = {
x: 1,
arr: [this.x, this.x, this.x],
};
console.log(obj.arr)
我应该如何引用数组中的 x ?我尝试用括号将 arr 括起来,但这只会给我一个语法错误。我尝试搜索这将如何工作,但没有发现任何有用的东西......
此外,我希望该 arr 是二维的,这样:
var obj = {
x: 1,
arr: [
[this.x, this.x, this.x],
[this.x, this.x, this.x],
[this.x, this.x, this.x]
],
};
console.log(obj.arr);
那么它会如何工作?
最佳答案
你不能在对象中引用this
,this适用于函数。要访问该属性,您可以分配和重用。
相反,使用 ES6 可以简化它。但在这种情况下你不能再把它调回去。它将是只读的。
检查示例。
var obj = {
x: 1
};
obj.arr = [obj.x, obj.x, obj.x]
console.log(obj.arr)
/// Other way arround , USING ES6 get
var obj = {
x: 1,
get arr() {
return [this.x, this.x, this.x];
},
};
console.log(obj.arr); // [1,1,1]
obj.arr = [1] // modify
console.log(obj.arr); // [1,1,1] still same
.as-console-row {
color: blue !important;
}
关于javascript - 在 JavaScript 中将属性嵌套在属性数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61034371/