简体   繁体   中英

Why js variable show [object object] but console.log() works?

I have some codes

var weibo = { weibo: { url: '//testurl.com', icon: 'fa fa-weibo' } }
var mail = { mail: { url: '//testurl.com', icon: 'fa fa-envelope' } }
var github = { github: { url: '//testurl.com', icon: 'fa fa-github' } }

var [key] = Object.keys(weibo)
var name = weibo[key]
console.log(weibo[key])

I want to get object from weibo and store into name variable

But name show [object object]

在此处输入图片说明

I am not use alert from What does [object Object] mean? (JavaScript)

key is a string weibo 在此处输入图片说明

I just want to store variable into name, why chrome dev tools show [object object] ?

console.log() works, it show corrent object info 在此处输入图片说明

Update please see my gif


This had me thinking for a while, turns out there is a window.name global variable defined in browsers ( MDN:Window.name ).

According to MDN: window.name will convert all values to their string representations by using the toString method.

When toString is applied to an object, the output will be [object object] .

So either enclose your piece of code within its own scope (probably inside a function) or rename your name variable.

use

var key = Object.keys(weibo)
var name = key[0]

这是因为您已创建“ weibo”作为对象,并将其传递给原始数据类型引用“ name”。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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