javascript 无法访问对象属性,即使它显示在控制台日志中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17546953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:43:11  来源:igfitidea点击:

Can't access object property, even though it shows up in a console log

javascriptconsole.log

提问by Brian Litzinger

Below, you can see the output from these two logs. The first clearly shows the full object with the property I'm trying to access, but on the very next line of code, I can't access it with config.col_id_3(see the "undefined" in the screenshot?). Can anyone explain this? I can get access to every other property except field_id_4as well.

下面,您可以看到这两个日志的输出。第一个清楚地显示了具有我试图访问的属性的完整对象,但在下一行代码中,我无法访问它config.col_id_3(请参阅屏幕截图中的“未定义”?)。谁能解释一下?我可以访问除此之外的所有其他属性field_id_4

console.log(config);
console.log(config.col_id_3);

This is what these lines print in Console

这是这些行在控制台中打印的内容

Console output

控制台输出

采纳答案by Matt

The output of console.log(anObject)is misleading; the state of the object displayed is only resolved when you expand the >in the console. It is notthe state of the object when you console.log'd the object.

的输出具有console.log(anObject)误导性;显示对象的状态仅在您>在控制台中展开时才会解析。当你得到对象时,它不是对象的状态console.log

Instead, try console.log(Object.keys(config)), or even console.log(JSON.stringify(config))and you will see the keys, or the state of the object at the time you called console.log.

相反,尝试console.log(Object.keys(config)),甚至console.log(JSON.stringify(config)),您将看到键,或调用时对象的状态console.log

You will (usually) find the keys are being added afteryour console.logcall.

您(通常)会console.log致电发现正在添加密钥。

回答by ramin

I've just had this issue with a document loaded from MongoDB using Mongoose.

我刚刚遇到了使用Mongoose从 MongoDB 加载的文档的问题。

When running console.log()on the whole object, all the document fields (as stored in the db) would show up. However some individual property accessors would return undefined, when others (including _id) worked fine.

console.log()整个对象上运行时,所有文档字段(存储在数据库中)都会显示出来。然而undefined,当其他属性访问器(包括_id)工作正常时,某些单独的属性访问器会返回。

Turned out that property accessors only works for those fields specified in my mongoose.Schema(...)definition, whereas console.log()and JSON.stringify()returns all fields stored in the db.

原来,属性访问器仅适用于我的mongoose.Schema(...)定义中指定的那些字段,而console.log()JSON.stringify()返回存储在数据库中的所有字段。

Solution (if you're using Mongoose): make sure all your db fields are defined in mongoose.Schema(...).

解决方案(如果您使用的是 Mongoose):确保您的所有 db 字段都在mongoose.Schema(...).

回答by Asaf Lopez

Check if inside the object there's an array of objects. I had a similar issue with a JSON:

检查对象内部是否有对象数组。我对 JSON 有类似的问题:

    "terms": {
        "category": [
            {
                "ID": 4,
                "name": "Cirugia",
                "slug": "cirugia",
                "description": "",
                "taxonomy": "category",
                "parent": null,
                "count": 68,
                "link": "http://distritocuatro.mx/enarm/category/cirugia/"
            }
        ]
    }

I tried to access the 'name' key from 'category' and I got the undefinederror, because I was using:

我试图从“类别”访问“名称”键,但出现未定义错误,因为我使用的是:

var_name = obj_array.terms.category.name

Then I realised it has got square brackets, that means that it has an array of objects inside the category key, because it can have more than one category object. So, in order to get the 'name' key I used this:

然后我意识到它有方括号,这意味着它在类别键内有一组对象,因为它可以有多个类别对象。因此,为了获得“名称”键,我使用了这个:

var_name = obj_array.terms.category[0].name

And That does the trick.

这就是诀窍。

Maybe it's too late for this answer, but I hope someone with the same problem will find this as I did before finding the Solution :)

也许这个答案为时已晚,但我希望有同样问题的人会像我在找到解决方案之前一样找到这个:)

回答by Tope

I had the same issue. Solution for me was using the stringified output as input to parsing the JSON. this worked for me. hope its useful to you

我遇到过同样的问题。我的解决方案是使用字符串化的输出作为解析 JSON 的输入。这对我有用。希望对你有用

var x =JSON.parse(JSON.stringify(obj));
console.log(x.property_actually_now_defined);

回答by Lai Xue

The property you're trying to access might not exist yet. Console.log works because it executes after a small delay, but that isn't the case for the rest of your code. Try this:

您尝试访问的属性可能还不存在。Console.log 之所以有效,是因为它会在一小段延迟后执行,但对于您的其余代码,情况并非如此。试试这个:

var a = config.col_id_3;    //undefined

setTimeout(function()
{
    var a = config.col_id_3;    //voila!

}, 100);

回答by rolinger

In my case I was passing an object to a promise, within the promise I was adding more key/values to the object and when it was done the promise returned the object.

在我的例子中,我将一个对象传递给一个 promise,在 promise 中我向对象添加了更多的键/值,当它完成时,promise 返回了对象。

However, a slight over look on my part, the promise was returning the object before it was fully finished...thus the rest of my code was trying to process the updated object and the data wasn't yet there. But like above, in the console, I saw the object fully updated but wasn't able to access the keys - they were coming back undefined. Until I saw this:

然而,我稍微看了一下,承诺在它完全完成之前返回对象......因此我的其余代码正在尝试处理更新的对象,而数据尚未存在。但是像上面一样,在控制台中,我看到对象完全更新但无法访问密钥 - 它们返回未定义。直到我看到了这个:

console.log(obj) ;
console.log(obj.newKey1) ;

// returned in console
> Object { origKey1: "blah", origKey2: "blah blah"} [i]
    origKey1: "blah"
    origKey2: "blah blah"
    newKey1: "this info"
    newKey2: "that info"
    newKey3: " more info"
> *undefined*

The [i] is a little icon, when I hovered over it it said Object value at left was snapshotted when logged, value below was evaluated just now. Thats when it occurred to me that my object was being evaluated before the promise had fully updated it.

[i] 是一个小图标,当我将鼠标悬停在它上面时,它说Object value at left was snapshotted when logged, value below was evaluated just now。那是我突然想到我的对象在承诺完全更新它之前正在被评估。

回答by Jette

I struggled with this issue today, and thought I'll leave a reply with my solution.

我今天在这个问题上挣扎,我想我会留下我的解决方案的答复。

I was fetching a data object via ajax, something like this: {"constants": {"value1":"x","value2":"y"},"i18n" {"data1":"x", "data2":"y"}}

我正在通过 ajax 获取数据对象,如下所示: {"constants": {"value1":"x","value2":"y"},"i18n" {"data1":"x", "data2":"y"}}

Let's say this object is in a variable called data. Whenever I referenced data.i18nI got undefined.

假设这个对象在一个名为 data 的变量中。每当我引用时,data.i18n我都会得到undefined.

  1. console.log(data)showed the object as expected
  2. console.log(Object.keys(data))said ["constants","i18n"]as expected
  3. Renaming i18nto interdidn't change anything
  4. I even tried to switch the data to make "i18n" the first object
  5. Moved code around to make absolutely sure the object was completely set and there was no problem with the ajax promise.
  1. console.log(data)按预期显示对象
  2. console.log(Object.keys(data))["constants","i18n"]正如预期的那样说
  3. i18n重命名为inter没有改变任何东西
  4. 我什至尝试切换数据使“i18n”成为第一个对象
  5. 移动代码以确保完全设置对象并且ajax承诺没有问题。

Nothing helped... Then on the server side I wrote the data to the php log, and it revealed this:

没有任何帮助......然后在服务器端我将数据写入php日志,它揭示了这一点:

{"constants": {"value1":"x","value2":"y"},"\u045618n" {"data1":"x", "data2":"y"}}

{"constants": {"value1":"x","value2":"y"},"\u045618n" {"data1":"x", "data2":"y"}}

The "i" in the index key was actually a u0456 (cyrillic i). This was not visible in my php editor or the browser console log. Only the php log revealed this... That was a tricky one...

索引键中的“i”实际上是一个 u0456(西里尔字母 i)。这在我的 php 编辑器或浏览器控制台日志中是不可见的。只有 php 日志揭示了这一点......这是一个棘手的......

回答by makkasi

My data was just json data string . (This variable was stored as json string in the session).

我的数据只是 json 数据字符串。(此变量在会话中存储为 json 字符串)。

console.log(json_string_object)

-> returns just the representation of this string and there is no way to make difference whether is string or object.

-> 仅返回此字符串的表示形式,无法区分是字符串还是对象。

So to make it work I just needed to convert it back to real object:

所以为了让它工作,我只需要将它转换回真实对象:

object = JSON.parse(json_string_object);

回答by MTZ

In 2018 Mozilla warns us in the Mozilla Docs here!

2018 年,Mozilla 在此处Mozilla 文档中警告我们!

I quote "Logging Objects":

我引用“记录对象”

Don't use console.log(obj);,use console.log(JSON.parse(JSON.stringify(obj)));.

This way you are sure you are seeing the value of obj at the moment you log it.

不要用console.log(obj);console.log(JSON.parse(JSON.stringify(obj)));

通过这种方式,您可以确定在记录时看到 obj 的值。

回答by user_CC

This might help somebody as I had a similar issue in which the JSON.parse() was returning an object that I could print on the console.log() but I couldn't acccess the specific fields and none of the above solution worked for me. Like using the combination of JSON.parse() with JSON.stringify().

这可能对某人有所帮助,因为我有一个类似的问题,其中 JSON.parse() 返回一个对象,我可以在 console.log() 上打印该对象,但我无法访问特定字段,并且上述解决方案均无效我。就像使用 JSON.parse() 和 JSON.stringify() 的组合。

var jsonObj = JSON.parse(JSON.stringify(responseText))

// where responseText is a JSON String returned by the server.

console.log(jsonObj) ///Was printing the object correctly
console.log(jsonObj.Body) /// Was printing Undefined  

I ended up solving the problem by using a different parser provided by ExtJs Ext.decode();

我最终通过使用 ExtJs Ext.decode(); 提供的不同解析器解决了这个问题;

var jsonObj = Ext.decode(responseText)
console.log(jsonObj.Body) //Worked...