gpt4 book ai didi

javascript - 计算数组中的对象数,忽略 null

转载 作者:行者123 更新时间:2023-11-28 10:42:42 24 4
gpt4 key购买 nike

我还很初级,如果不合适请见谅。

尝试计算数组中的对象数,忽略 null。这是我到目前为止的代码:

    function countTheObjects (arr) {

let count = 0;

for (let i = 0; i < arr.length; i++) {
if (typeof arr[i] === 'object') {
count++;
}
if (arr[i] === null) {
count--;
}


}
return count;
}

我做错了什么?

编辑:

你们给我的所有这些代码都返回与我的错误完全相同的错误。这些是代码必须通过的测试:

describe('countTheObjects', function () {
it('returns the count of objects inside an array of random data types', function () {
expect(countTheObjects([])).to.equal(0);
expect(countTheObjects([1, 3, 4, 5])).to.equal(0);
expect(countTheObjects([1, 3, 4, 5, 'foo'])).to.equal(0);
expect(countTheObjects([1, 3, 4, 5, {}, {}, {}, 'foo'])).to.equal(3);
expect(countTheObjects([1, [], 3, 4, 5, {}, {}, {}, 'foo'])).to.equal(3);
expect(countTheObjects([1, [], null, 3, 4, 5, {}, {}, {}, 'foo'])).to.equal(3);
expect(countTheObjects([1, {}, [], null, null, 'foo', 3, 4, 5, {}, {}, {}, 'foo'])).to.equal(4);
});
});

最佳答案

你的代码是错误的,因为typeof null ===“object”

function countTheObjects (arr) {
let count = 0;

arr.forEach(e => {
if (typeof e === "object" && e !== null) {
count++;
}
});

return count;
}


alert(countTheObjects([
1, 2, 3, null, null, 5, 6, null, {}, {}, {}
]));

关于javascript - 计算数组中的对象数,忽略 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49439730/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com