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

标签 javascript arrays javascript-objects

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

尝试计算数组中的对象数,忽略 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/

相关文章:

javascript - Node 中具有原型(prototype)的单例对象

javascript - 达到限制后使数字变量不可变

javascript - 从手机或计算机检测用户并在不同位置显示广告

javascript - 如何从动态创建的按钮传递参数?

c - fopen() 修改 char 数组的奇怪错误? [C语言]

Javascript 整数数组错误

javascript - 使用 Ajax 发送 Javascript 对象时未定义的数据

javascript - Plotly 中的多个 X 轴

javascript - 完全合并两个多维数组并生成一个新数组

javascript - 自定义排序对象数组