简体   繁体   English

初始化键值对 Javascript 对象

[英]Initializing key and value pairs Javascript Object

I've seen developers declare an empty object and later assign properties and values to it but I mostly create an object and initialize the properties and values.我见过开发人员声明一个空对象,然后为其分配属性和值,但我主要是创建一个对象并初始化属性和值。 Example例子

const data = {}
data.name = "John Doe";
data.age = 60;

What I mostly do is :我主要做的是:

const data = {
name: "John Doe",
age: 60
}

I will like to know the difference between the two and why will you pick one over the other.我想知道两者之间的区别,以及为什么你会选择一个而不是另一个。 Thanks谢谢

Technically there is not much difference if you are declaring and assigning values immediately.从技术上讲,如果您立即声明和分配值,则没有太大区别。 But if you have to populate conditionally then the first option is better.但是,如果您必须有条件地填充,那么第一个选项会更好。 However you can also conditionally update a populated object.但是,您也可以有条件地更新填充的对象。

Declaring objects in Javascript is easiest than other programming languages.在 Javascript 中声明对象比其他编程语言更容易。 For example in C# (or Java), first you must declare structure of object, then you create an instance of that.例如在 C#(或 Java)中,首先你必须声明对象的结构,然后你创建它的一个实例。

using System;

namespace Example
{
    public struct Person
    {
        public string Name;
        public int Age;
        public Person(string name, int age)
        {
            Name = name;
            Age = age;
        }
    }

    public class Application
    {
        static void Main()
        {
            Person p1 = new Person("John Doe", 60);
            Console.WriteLine("p1 Name = {0} Age = {1}", p1.Name, p1.Age);
        }
    }
}

But in Javascript you can declare structure of object or not.但是在 Javascript 中,您可以声明或不声明对象的结构。 Even you can modify that structure after declaring.即使您可以在声明后修改该结构。 That's amazing (maybe not).这太棒了(也许不是)。 This feature of Javascript can produce many problems. Javascript 的这个特性会产生很多问题。

So, there is no difference.所以,没有区别。 But if you declare the structure, code will be more cleaner.但是如果你声明结构体,代码会更简洁。

For more information:了解更多信息:

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

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