用零填充对象
Filling object with zeros
我有一些函数可以计算数组中某些元素的数量:
let array = [5,1,2,3,4,7,2,1,2,3,4,5];
function countEntries(arr){
let entries = {};
arr.forEach(function (item) {
entries[item] += 1;
});
console.log(entries);
}
但是没有定义默认值,这是我得到的:
{ '1': NaN, '2': NaN, '3': NaN, '4': NaN, '5': NaN, '7': NaN }
我试图在 forEach
中定义一个对象的属性:
arr.forEach(function (item) {
entries[item] = 0;
entries[item] += 1;
});
但在这种情况下,属性 在每次迭代时都重置为零。事先不知道对象的属性名称怎么办?
有条件地添加默认值(可以使用逻辑或)
entries[item] = entries[item] || 0
let array = [5, 1, 2, 3, 4, 7, 2, 1, 2, 3, 4, 5];
function countEntries(arr) {
let entries = {};
arr.forEach(function(item) {
entries[item] = entries[item] || 0;
entries[item] += 1;
});
console.log(entries);
}
countEntries(array);
或者简单地说:
let array = [5,1,2,3,4,7,2,1,2,3,4,5]
, entries = {}
for(let e of array) entries[e] = (entries[e]) ? (entries[e]+1) : 1
console.log( JSON.stringify(entries) )
这是 reduce
的一个很好的用例:
const countEntries = array =>
array .reduce ((a, n) => ({...a, [n]: (a[n] || 0) + 1}), {})
let array = [5, 1, 2, 3, 4, 7, 2, 1, 2, 3, 4, 5];
console .log (
countEntries (array)
)
你走对了!您只需要将条件放入 forEach:
entries[item] ? entries[item] += 1 : entries[item]= 1;
表示如果该项目已经在 "entries" 对象中,则增加数量,如果没有 - 分配 1。
完整代码为:
function countEntries(arr){
let entries = {};
arr.forEach(function (item) {
entries[item] ? entries[item] += 1 : entries[item] = 1;
});
console.log(entries);
}
我有一些函数可以计算数组中某些元素的数量:
let array = [5,1,2,3,4,7,2,1,2,3,4,5];
function countEntries(arr){
let entries = {};
arr.forEach(function (item) {
entries[item] += 1;
});
console.log(entries);
}
但是没有定义默认值,这是我得到的:
{ '1': NaN, '2': NaN, '3': NaN, '4': NaN, '5': NaN, '7': NaN }
我试图在 forEach
中定义一个对象的属性:
arr.forEach(function (item) {
entries[item] = 0;
entries[item] += 1;
});
但在这种情况下,属性 在每次迭代时都重置为零。事先不知道对象的属性名称怎么办?
有条件地添加默认值(可以使用逻辑或)
entries[item] = entries[item] || 0
let array = [5, 1, 2, 3, 4, 7, 2, 1, 2, 3, 4, 5];
function countEntries(arr) {
let entries = {};
arr.forEach(function(item) {
entries[item] = entries[item] || 0;
entries[item] += 1;
});
console.log(entries);
}
countEntries(array);
或者简单地说:
let array = [5,1,2,3,4,7,2,1,2,3,4,5]
, entries = {}
for(let e of array) entries[e] = (entries[e]) ? (entries[e]+1) : 1
console.log( JSON.stringify(entries) )
这是 reduce
的一个很好的用例:
const countEntries = array =>
array .reduce ((a, n) => ({...a, [n]: (a[n] || 0) + 1}), {})
let array = [5, 1, 2, 3, 4, 7, 2, 1, 2, 3, 4, 5];
console .log (
countEntries (array)
)
你走对了!您只需要将条件放入 forEach:
entries[item] ? entries[item] += 1 : entries[item]= 1;
表示如果该项目已经在 "entries" 对象中,则增加数量,如果没有 - 分配 1。
完整代码为:
function countEntries(arr){
let entries = {};
arr.forEach(function (item) {
entries[item] ? entries[item] += 1 : entries[item] = 1;
});
console.log(entries);
}