Object.values() 的替代版本 [英] Alternative version for Object.values()

查看:43
本文介绍了Object.values() 的替代版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找 Object.values() 函数的替代版本.
正如此处所述,该函数不是支持 Internet Explorer.

I'm looking for an alternative version for the Object.values() function.
As described here the function is not supported in Internet Explorer.

执行以下示例代码时:

var obj = { foo: 'bar', baz: 42 };
console.log(Object.values(obj)); // ['bar', 42]

它适用于 Firefox 和 Chrome,但在 IE11 中会引发以下错误:

It works in both, Firefox and Chrome, but throws the following error in IE11:

对象不支持属性或方法值"

Object doesn't support property or method "values"

在这里你可以测试它:Fiddle.

Here you can test it: Fiddle.

那么,什么是快速修复?

So, what would be a quick fix?

推荐答案

您可以使用 Object.keys() 获取键数组,然后使用 map()获取值.

You can get array of keys with Object.keys() and then use map() to get values.

var obj = { foo: 'bar', baz: 42 };
var values = Object.keys(obj).map(function(e) {
  return obj[e]
})

console.log(values)

在 ES6 中,您可以使用箭头函数将其写在一行中.

With ES6 you can write this in one line using arrow-functions.

var values = Object.keys(obj).map(e => obj[e])

这篇关于Object.values() 的替代版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆