gpt4 book ai didi

javascript - 如何在javascript中的数组内使用 "this"关键字?

转载 作者:行者123 更新时间:2023-11-28 06:09:30 29 4
gpt4 key购买 nike

这里我有一个数组,其中包含 n 个与此类似的对象。

var views = [
{
id: "chart-0",
datasource: "",
type: "batch",
context: "/analytics/device/stats/",
schema: [
{
"metadata": {
"names": [""],
"types": [""]
}
}
],
columns: [
{
"name": "month",
"label": "month",
"type": "linear",
},
{
"name": "minValue",
"label": "minValue",
"type": "linear"
},
{
"name": "maxValue",
"label": "maxValue",
"type": "linear",
"axis": "y"
},
{
"name": "time",
"label": "time",
"type": "time",
"axis": "x"
},
],
callbacks: [
{
type: "click",
callback: function() {}
}
],
data: function() {
var COLUMNS = views[0].columns;
}
}
];

我想访问data函数中的一些字段。我可以简单地访问 id、数据源 this.idthis.datasource。如何使用 this 关键字而不是 views[0].columns 访问数据函数内的

最佳答案

我知道您可以使用 this 关键字来分配 id、距离或任何其他属性的唯一方法是将数据传递到函数中。

// create a function and pass in a reference to the views array and specify the objects index you want to operate on.

function chanceProperty( views[0]) {
var currentColumns = this.columns; // gives you a reference to the objects columns array. "This" is a reference to the object that was passed in.

// you can then do your operations on the properties in that array either with a loop or by specifically targeting an object.

currentColumns[1].name = "myNewMinValue";

// or

currentColumns.forEach( function(val, idx) {
currentColumns[idx].name = "allTheSame";
});

}

更新

我想我明白你想做什么。您希望将一些 View 属性传递给数据函数。你不需要“这个”。您只需将所需的属性传递给数据函数即可。

data: function(id, dataSource, columns) {
var COLUMNS = views[0].columns;
}

关于javascript - 如何在javascript中的数组内使用 "this"关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36539042/

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