JavaScript:浏览器控制台如何显示对象键值

时间:2018-09-19 17:04:07

标签: javascript google-chrome google-chrome-devtools undefined google-chrome-console

在Chrome控制台中:

> myParam = {"test": "test value"}    
> myFunc = function(x) { myParam[x] = x; }

> myFunc("func value")
> myParam
{test: "test value", func value: "func value"} // (a) question

> myFunc(2)
> myParam
{2: 2, test: "test value", func value: "func value"}

> myFunc()
> myParam
{2: 2, test: "test value", func value: "func value", undefined: undefined} // (b) question

这是迄今为止的最新版本的Chrome(69.0.3497.100) enter image description here
请解释如何使用JavaScript

a)可以创建一个包含空格(“ myParam.func值”)的对象成员
  b)可以创建一个“未定义”对象成员(“ myParam.undefined”)
  c)对于(b)情况,“未定义”是真的“未定义”还是只是字符串“未定义”?


PS。由于@ryanpcmcquen的评论,以下PS enter image description here


PPS。。如果字符串不像字符串那样显示,您能否确认我的假设是Google Chrome v(69.0.3497.100)控制台显示错误,“在方括号之间”和红色?


PPS。
只有 Firefox 似乎可以正确显示字符串键:

Chrome浏览器,Opera
enter image description here
Firefox
enter image description here
边缘
enter image description here
MS IE
enter image description here

4 个答案:

答案 0 :(得分:3)

考虑对象foo

var foo = {};

a)可以创建一个包含空格(“ myParam.func值”)的对象成员

// You have to use square bracket notation when
// declaring properties with spaces.
foo['func value'] = 'Whatever you want.';

b)可以创建一个“未定义”对象成员(“ myParam.undefined”)

// Keyword undefined:
foo[undefined] = undefined;
// String 'undefined':
foo['undefined'] = 'undefined';

c)对于(b)情况,“未定义”是真的“未定义”还是只是字符串“未定义”?

取决于您如何定义它。在屏幕快照中,属性值是关键字undefined,密钥是字符串'undefined'

要验证对象内部的类型,可以运行:

Object.keys(foo).map(key => typeof key);
Object.values(foo).map(value => typeof value);

答案 1 :(得分:0)

这是JavaScript的优点之一。

a)我们可以用空格创建对象键,因为对象键可以是字符串。当您想查看其键为String的对象的值时,需要按以下方式进行操作

var a = {
  'my key': 'my key'
  yourKey: 'your key'
}
a['my key'];
a.yourKey

b)在JavaScript中,undefined是一种数据类型,因此拥有未定义值的变量是完全合法的

c)确实是不确定的。在此处查看更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined

答案 2 :(得分:0)

让我们回答您的问题。

a)可以创建一个包含空格(“ myParam.func值”)的对象成员

const myParam = {}
myParam["func value"] = 'serge';
console.log(myParam)

,但是只能使用方括号符号访问具有空格或连字符或以数字开头的属性名称

b)可以创建一个“未定义”对象成员(“ myParam.undefined”)

。对象属性名称可以是任何有效的JavaScript字符串,也可以是任何可以转换为字符串的内容,包括空字符串

const myParam = {};
myParam.undefiend = 'serge';
console.log(myParam)

c)(b)情况是“未定义”是真的“未定义”还是只是字符串“未定义”?

我猜这是字符串“ undefined”

答案 3 :(得分:-3)

将c“未定义”的答案通常朝向“ null”值,您可以console.log(null)并找到未定义

相关问题