简体   繁体   English

如何根据 Object 中其他键的值自动将值分配给另一个键

[英]How to automatically assign value to another key depending on some other key's value in an Object

How do you achieve the following thing in Javascript你如何在Javascript中实现以下目标

1) var MyObject={
2)    tableView:true,
3)    chartView:!(this.tableView)
4) }

The code at line number 3 is not working.第 3 行的代码不起作用。 Whats wrong in that line?那一行有什么问题?

What i basically want to do is set "chartView" to opposite of "tableView" whenever tableView is set from code.我基本上想要做的是在从代码设置 tableView 时将“chartView”设置为“tableView”的对面。

Since you're in the process of creating the object, this is not bound to that object. Moreover, since you want chartView to always evaluate to the opposite of tableView , even if the latter changes further down the line, a function would be a better approach:由于您正在创建 object, this它不受 object 的约束。此外,由于您希望chartView始终计算为tableView的相反值,即使后者进一步更改,function 也将是更好的方法:

var MyObject = {
    tableView: true,
    chartView: function() {
        return !this.tableView;
    }
};

Now you can do:现在你可以这样做:

var chartView = MyObject.chartView();  // false.
MyObject.tableView = false;
chartView = MyObject.chartView();      // true.

You can't use this to refer to an object in an object literal's properties.您不能使用它来引用 object 文字属性中的 object。 You can use this inside a function that is a method of that object:您可以在 function 中使用它,它是 object 的一种方法:

var MyObject = {
  tableView: true,
  chartView: function () {
    return !this.tableView;
  }
}

Based on your requirement, this may be an answer too,根据您的要求,这也可能是一个答案,

 var MyObject = {
      view : function(bool){
         this.tableView = bool;
         this.chartView = !(bool); 
      }
      tableView: true,
      chartView: false
    } 

    MyObject.view(false)

    console.log(MyObject.tableView);     // Outputs false
    console.log(MyObject.chartView)      // Outputs true

This way you will always have opposite of tableView in chartView with a single function call.这样,通过一次 function 调用,您将始终与 chartView 中的 tableView 相反。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM