简体   繁体   English

为什么JS要求存在对象/数组

[英]Why does JS require object/array to be present

I've been working angular for probably six or so months and so have been working a lot more with JSON and objects in javascript. 我已经从事了大约六个月的开发工作,因此在JSON和javascript中的对象方面进行了更多工作。 This situation I've been running into has been frustrating and I don't understand the reasoning. 我一直遇到的这种情况令人沮丧,我不明白其原因。 Maybe it's my inexperience with JS and so I don't know the reasoning or maybe I'm just doing it wrong but I'd appreciate any insight into this. 也许这是我对JS的经验不足,所以我不知道其原因,或者我做错了,但我希望对此有所了解。

Example an object: 示例对象:

    var data = 
   {  
   "object":
       {  
         "Key":"Value",
         "stuff":"here"
       },
       "array":
       [  
          {  
            "Name":"Pizza Face",
            "id":7
          },
          {  
            "Name":"Maple bar",
            "id":1
          }
       ]
    }

So, let's say I want to add an object to the array. 因此,假设我要向该数组添加一个对象。 Easy, right? 容易吧?

var newObject = {"Name": "Master Sword", "id":2}
data.array.push(newObject);

But, let's say I want to add the object to the array before the array exists. 但是,假设我想在数组存在之前将对象添加到数组中。 The above method errors out saying Cannot read property 'push' of undefined . 上面的方法错误地指出Cannot read property 'push' of undefined Instead, I have to wrap a condition around it. 相反,我必须围绕它包装一个条件。

  var newObject = {"Name": "Master Sword", "id":2}
  if(data.array){
    data.array.push(newObject);
  }
  else{
    data.array = [];
    data.array.push(newObject);
  }

I am allowed to add new objects to data whenever I want. 我可以随时在data添加新对象。 However, woe unto me should I try to add an object within an object. 但是,我应该在一个对象中添加一个对象给我带来麻烦。

Example: 例:

data.newObject = {"Name": "Master Sword", "id":2}

newObject will be created in this case and everyone is happy. 在这种情况下将创建newObject,每个人都很高兴。

data.newObject.Name = "Master Sword"

FAIL! 失败! Cannot set property 'Name' of undefined

So...why doesn't JS just create newObject with the laid out key value pair? 那么...为什么JS不只是使用布局键值对创建newObject? Or when I try to push to an array that doesn't exist why not just create the array rather than error out? 或者,当我尝试推送到不存在的数组时,为什么不创建数组而不是出错呢?

I want to be clear, although this is frustrating to me my purpose of this question isn't to complain. 我想明确一点,尽管这让我感到沮丧,但我对这个问题的目的不是抱怨。 It's to ask if I'm doing this wrong. 问我是否做错了。 Do I really need a condition to check if the object/array exists before trying to add to it? 在尝试添加对象/数组之前,我真的需要条件来检查该对象/数组是否存在吗? Is there a better way to do this? 有一个更好的方法吗?

You are trying to create objects via chaining . 您正在尝试通过chaining创建对象。 The problem with that is except the last part in the chain, all the previous ones must be already defined Javascript Objects . 这样做的问题是,除了链中的最后一部分之外,所有先前的部分都必须已经定义了Javascript Objects

a.b.c.d = new Object(); // a,b,c must be already defined, cannot have cascading here

So, when you say data.newObject.Name = "Master Sword"; 因此,当您说data.newObject.Name = "Master Sword"; , the newObject should have been defined earlier (you already had a data object I assume). ,则应早先定义newObject (我已经假设有一个data对象)。 This is how it has to work (probably in every language that follows at least some semantics). 这就是它的工作方式(可能是在至少遵循某些语义的每种语言中)。 To get around such a problem, you can always create a new generic object say: 为了解决这个问题,您总是可以创建一个新的通用对象,例如:

var myComplexObject = function() { //add all reusable object constructors here  };

Populate your complex object any way you like, eg creating a new empty object in this constructor and add Prototypes to this constructor to expand the functionality. 以您喜欢的任何方式填充您的复杂对象,例如,在此constructor创建一个新的空对象,并将Prototypes添加到此构造函数以扩展功能。 Write once and iterate forever over that. 编写一次,然后对其进行永远的迭代。 You could build a library suited to your requirements. 您可以构建适合您需求的库。 That is how it should be done. 那是应该做的。

PS: Probably, for the checking part you could encapsulate in a try{}catch(e){} block. PS:也许,对于检查部分,您可以将其封装在try{}catch(e){}块中。

The method push is located on a javascript Array object, unsurprisingly that method will not work on either null or undefined . 方法push位于javascript Array对象上,毫不奇怪,该方法对nullundefined都不起作用。 This is the same for pretty much every programming language. 几乎每种编程语言都一样。

When calling data.newObject = {"Name": "Master Sword", "id":2} you are quite literally setting the property to a new object, this is a very different scenario to the above. 当调用data.newObject = {"Name": "Master Sword", "id":2}时,实际上是将该属性设置为一个新对象,这与上述情况截然不同。

That´s because when you try to reference a key of an object, if that key doesn´t exist then that key will be kind of created and the undefined value will be assigned to it. 那是因为当您尝试引用对象的键时,如果该键不存在,则将创建该键,并为其分配未定义的值。 undefined is just a JS Value type. undefined只是一个JS Value类型。 If you want to check that "undefined" is not an error, just note that "undefined" is written with gray color on the console. 如果要检查“ undefined”不是错误,请注意在控制台上用灰色写了“ undefined”。 (Errors have the red color). (错误显示为红色)。

If you assign an object to a key of other object, and you want to add properties to it, that won´t represent a problem at all. 如果将一个对象分配给其他对象的键,并且要向其添加属性,那根本就不会出现问题。

But if you try to add a property to a key that can be initialized with undefined value, then it's reasonable that you will get an error message. 但是,如果您尝试将属性添加到可以使用未定义值初始化的键中,那么您将收到一条错误消息是合理的。 Remember, JS allows you to store any value type you want on objects. 请记住,JS允许您将所需的任何值类型存储在对象上。

I suggest you to read a little bit more about objects, and the undefined value in JavaScript. 我建议您多读一些有关对象以及JavaScript中未定义的值的信息。

Hope that it helps. 希望对您有所帮助。

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

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