在JavaScript中初始化对象的空属性的正确方法是什么 [英] What is the correct way to initialise an empty property of an object in JavaScript

查看:77
本文介绍了在JavaScript中初始化对象的空属性的正确方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有属性的对象,其中一个属性 prop2 只会在以后初始化并在准备就绪时添加到此对象。

I have an object that with properties, 1 of those properties prop2 will only be initialised later and added to this object when its ready.

我想将它显示为对象的属性,纯粹是为了人类的可读性,所以当我稍后查看代码时,我会知道它存在并且/可以使用。

I want to show it as a property of the object purely for human readability so that when I look at the code later I will know that it exists and will/can be used.

所以我的问题是:


什么是正确方法在JavaScript中初始化对象
的空属性

What is the correct way to initialise an empty property of an object in JavaScript



myObject = {
    prop1: 'somevalue',
    prop2: '' <---- ''|null|undefined|false|0|{} what is correct
    }

我假设它取决于将要使用的类型,我意识到任何实际工作,我感兴趣的是最佳做法

I am assuming it depends on the type that will be used, and I realise that anything actually works, I am interested in the best practice way.

Fiddler: http://jsfiddle.net/gamelodge/DWCEa/

推荐答案

我通常使用<$ c为此,$ c> null 。它与 undefined (不存在)不同,并且满足变量存在但没有值的要求。

I usually use null for this purpose. It is distinct from undefined (does not exist) and satisfies the requirement that the variable exists but has no value.

这篇关于在JavaScript中初始化对象的空属性的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆