简体   繁体   English

我可以为 JavaScript 中的 1 个定义分配 2 个 object 吗?

[英]Can I assign 2 object for 1 definition in JavaScript?

For example, I have the following data例如,我有以下数据

A : {  name: "Ball",
       color: { 
                out : ["red","black","green"],
                in : ["white","pink"]
               },
     }

I want to have another object to call with the same definition.我想要另一个 object 以相同的定义调用。 Can I do this?我可以这样做吗?

 A, B : {  name: "Ball",
           color: { 
                    out : ["red","black","green"],
                    in : ["white","pink"]
                   },
         }

If you're asking for the syntax to declare 2 fields with the same value, no you cannot do that.如果您要求使用语法来声明具有相同值的 2 个字段,那么您不能这样做。 You can however declare a separate variable and point both fields at that variable.但是,您可以声明一个单独的变量并将两个字段都指向该变量。

const myBall = {
  name: "Ball",
  color: {
    out: ["red", "black", "green"],
    in: ["white", "pink"]
  }
};

const myObject = {
  A: myBall,
  B: myBall
};

or if you're looking to create two discrete objects, you could write a function to create a new one for you.或者,如果您要创建两个离散对象,您可以编写一个 function 来为您创建一个新对象。

const createMyBall = () => ({
  name: "Ball",
  color: {
    out: ["red", "black", "green"],
    in: ["white", "pink"]
  }
});

const myObject = {
  A: createMyBall(),
  B: createMyBall()
};

assing to object评估 object

var a, b;
a = b =

 var a, b; a = b = { name: "Ball", color: { out: ["red","black","green"], in: ["white","pink"] }, }; console.log(a); console.log(b);

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

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