我有一个看起来像这样的对象:
let arr = {
names: ['John', 'Paul'],
phones: ['iPhone', 'Samsung', 'Huawei'],
clothesBrands: ['HM', 'Zara']
}Run Code Online (Sandbox Code Playgroud)
我需要对数组的长度求和。我可以这样做:
arr.names.length + arr.phones.length + arr.clothesBrands.length
Run Code Online (Sandbox Code Playgroud)
结果是7。
如果我不知道所有的键,我怎么能以干净的方式做到这一点?
您可以检查.flatTened 值数组的长度:
const arr = {
names: ['John', 'Paul'],
phones: ['iPhone', 'Samsung', 'Huawei'],
clothesBrands: ['HM', 'Zara']
};
console.log(Object.values(arr).flat().length);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
857 次 |
| 最近记录: |