[英]fat arrow with objects
Is there a way to use a fat arrow with an object? 有没有办法在对象上使用粗箭头?
The following code prints out the contents of the array "test" in the console. 以下代码在控制台中打印出数组“ test”的内容。
//With array
let test = [1, 2, 3, 4];
test.forEach(number => console.log(number));
I'm looking for a way to have the same output but with "test" being an object, not an array (like below). 我正在寻找一种具有相同输出,但将“ test”作为对象而不是数组的方法(如下所示)。 is there a (relatively) simple way of doing this?
有(相对)简单的方法吗?
//With object
let test = {
a: 1,
b: 2,
c: 3,
d: 4
}
test.forEach(number => console.log(number));
There is a couple of ways to do this: 有两种方法可以做到这一点:
Object.keys(test).forEach(key => console.log(test[key]));
Object.keys
is the oldest method, available since ES5. Object.keys
是最早的方法,自ES5起可用。
However, as you're using ES6 method you can probably use newer methods: 但是,当您使用ES6方法时,您可能可以使用更新的方法:
Object.keys(test) // ['a', 'b', 'c', 'd']
Object.values(test) // [1, 2, 3, 4]
Object.entries(test) // [['a', 1], ['b', 2], ['c', 3], ['d', 4]]
Array methods cannot be used on an object. 数组方法不能在对象上使用。 Use
Object.keys
to get an array of object's keys, then use array method forEach
使用
Object.keys
获取对象的关键点的数组,然后使用数组方法forEach
let test = { a: 1, b: 2, c: 3, d: 4 } Object.keys(test).forEach(number => console.log(test[number]));
for array you can use array.forEach()
and for object you need to use Object.values(object).forEach()
for values and Object.keys(object).forEach()
for object keys. 对于数组,您可以使用
array.forEach()
;对于对象,您需要使用Object.values(object).forEach()
作为值,而Object.keys(object).forEach()
作为对象键。 :D :D
//With array var test = [1, 2, 3, 4]; console.log("Array"); test.forEach(number => console.log(number)); console.log("Obejct"); //With object var testObj = { a: 1, b: 2, c: 3, d: 4 } Object.values(testObj).forEach(number => console.log(number));
You have following options 您有以下选择
1) Object.keys()
1)
Object.keys()
test = {
a: 1,
b: 2,
c: 3,
d: 4
}
Object.keys(test).forEach(key => console.log(test[key]))
Object.keys
returns an array of keys of the object it was called on. Object.keys
返回调用它的对象的键的数组。
2) Object.values()
2)
Object.values()
test = {
a: 1,
b: 2,
c: 3,
d: 4
}
Object.values(test).forEach(value=> console.log(value))
Object.values
Returns an array whose elements are the enumerable property values found on the object. Object.values
返回一个数组,其元素是在对象上找到的可枚举的属性值。
Or you can use Object.values()
或者您可以使用
Object.values()
let test = {
a: 1,
b: 2,
c: 3,
d: 4
}
Object.values(test).forEach(number => console.log(number));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.