我有一个如下所示的对象:
let arr = {
names: ['John', 'Paul'],
phones: ['iPhone', 'Samsung', 'Huawei'],
clothesBrands: ['HM', 'Zara']
}
我需要对数组的长度求和。我可以这样做:
arr.names.length + arr.phones.length + arr.clothesBrands.length
结果是 7。
如果我不知道所有的键,我该如何以干净的方式完成它?
最佳答案
您可以检查.flat
值数组的长度:
const arr = {
names: ['John', 'Paul'],
phones: ['iPhone', 'Samsung', 'Huawei'],
clothesBrands: ['HM', 'Zara']
};
console.log(Object.values(arr).flat().length);
关于javascript - 如何对对象内数组属性的长度求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54820496/