【问题标题】:How to get a listing of key value pairs in an object? [duplicate]如何获取对象中的键值对列表? [复制]
【发布时间】:2012-07-02 00:09:42
【问题描述】:

可能重复:
best way to get the key of a key/value javascript object

foo = {bar: "baz"}

如何获得 foo 中所有属性和值的列表?

【问题讨论】:

标签: javascript


【解决方案1】:

for in 循环可以为您提供键和值。记得使用const、let 或var 在strict mode 中声明变量。

for(const p in foo) {
    console.log (p, foo[p])
}

从控制台:

foo = {bar: "baz"}

Object
bar: "baz"
__proto__: Object

for(p in foo) { console.log (p, foo[p]) }
> bar baz

如果您正在循环的对象从其原型继承了属性,您可以使用Object.hasOwnProperty() 函数防止继承的属性被循环,如下所示:

for(const p in foo) {
    if (foo.hasOwnProperty(p)) {
        console.log (p, foo[p])
    }
}

【讨论】:

    【解决方案2】:

    对于您当前使用的不同平台,这可能会有所不同。如果您从终端运行,则使用print,如果您没有console 对象,则可以使用document.write() 等等。

    您可以使用/阅读以下内容来理解:

    var foo = {bar: "baz", boolean: true, num: 2}
    
    for (i in foo) {
    //checks to see where to print.
    if (typeof console === 'object') 
        console.log(i + ": " + foo[i]);
    else if (typeof document === 'object') 
        document.write(i + ": " + foo[i]);
    else 
        print(i + ": " + foo[i]);
    }
    

    或者,如果您在 Chrome/Firefox 中只说 console.log(foo),浏览器会为您执行循环突出显示并为您提供对象的漂亮打印,因此您实际上不需要执行上面显示的循环。

    你也可以用console.debug(foo)代替console.log(foo),区别很细微。你可以在http://getfirebug.com/wiki/index.php/Console_API阅读更多相关信息

    【讨论】:

      【解决方案3】:

      你可以循环遍历它:

      for(var i in foo) {
        console.log( i + ": " + foo[i] + "<br />");
      }
      

      Demo

      【讨论】:

        猜你喜欢
        • 2015-11-05
        • 1970-01-01
        • 2019-08-07
        • 2013-05-11
        • 2015-09-16
        • 1970-01-01
        • 2023-04-07
        • 2019-12-04
        • 2019-09-11
        相关资源
        最近更新 更多