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

时间:2018-03-22 22:54:52

标签: 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);
  });
});

7 个答案:

答案 0 :(得分:1)

您的代码错误,因为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, {}, {}, {}
]));    

答案 1 :(得分:0)

运行:

&#13;
&#13;
/** For the given set of queries find the Unique element
 *  count of an array using MO's Algorithum. */
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <unordered_map>
using namespace std;

struct Query   // struct for storing the queries
{
    int Left;
    int Right;
    int Index;
};

inline void Add(const int i, int &ans, vector<int> &Arr, vector<int> &countArray)
{
    ++countArray[Arr[i]];
    if(countArray[Arr[i]] == 1)
            ans += countArray[Arr[i]];
    if(countArray[Arr[i]] == 2)
            ans -= countArray[Arr[i]];
}


inline  void Remove(const int i, int &ans, vector<int> &Arr, vector<int> &countArray)
{
    --countArray[Arr[i]];
    if(countArray[Arr[i]] == 1)
            ans += countArray[Arr[i]];
    if(countArray[Arr[i]] == 0)
            ans -= countArray[Arr[i]];
}

int main()
{
    int _size;    cin >> _size;

    vector<int> Arr;                            Arr.reserve(_size);
    copy_n(istream_iterator<int>(cin), _size, back_inserter(Arr));
    //copy(Arr.cbegin(), Arr.cend(), ostream_iterator<int>(cout, "\t"));

    int id = -1;
    int sqrt_n = sqrt(_size);
    int Q;      cin >> Q;
    vector<Query> qArr(Q);
    unordered_map<int, int> Map;

    for (int i = 0; i < _size; ++i)
    {
        if (Map.count(Arr[i]) == 0)
            Map[Arr[i]] = ++id;
        Arr[i] = Map[Arr[i]];
    }

    // read queries
    for (int i = 0; i < Q; ++i)
    {
        int L,R;
        cin >> L >> R;
        qArr[i].Left  = L-1;
        qArr[i].Right = R-1;
        qArr[i].Index = i;
    }
    // sort the queries according to(MO's Algorithum)
    sort(qArr.begin(),qArr.end(),
         [&](const Query &lhs, const Query &rhs)->bool
         {
             return ( (lhs.Left/sqrt_n == rhs.Left/sqrt_n) ?
                                    lhs.Right < rhs.Right:  // Qs with same Left case
              (lhs.Left / sqrt_n) < (rhs.Left / sqrt_n) );  // Qs with diff values case
         });

    int currStart = 0;
    int currEnd   = 0;
    int tempAnswer= 0;
    vector<int> Answer(Q);
    vector<int> countArray(_size);
    for (int i = 0; i < Q; ++i)
    {
        int L = qArr[i].Left;
        int R = qArr[i].Right;

/** Remove extra elements of previous range. For
 *  example if previous range is [0, 3] and current
 *  range is [2, 5], then a[0] and a[1] are subtracted */
        while (currStart < L)
        {
            Remove(currStart, tempAnswer, Arr, countArray);
            ++currStart;
        }
/** Add Elements of current Range */
        while (currStart > L)
        {
            Add(currStart - 1, tempAnswer, Arr, countArray);
            --currStart;
        }

        while (currEnd <= R)
        {
            Add(currEnd, tempAnswer, Arr, countArray);
            ++currEnd;
        }

/** Remove elements of previous range.  For example
 *  when previous range is [0, 10] and current range
 *  is [3, 8], then a[9] and a[10] are subtracted   */
        while (currEnd > R + 1)
        {
            Remove(currEnd - 1, tempAnswer, Arr, countArray);
            --currEnd;
        }
        Answer[qArr[i].Index] = tempAnswer;
    }

    for(const auto &it: Answer) cout<<it<<endl;

    return 0;
}
&#13;
&#13;
&#13;

您的测试期望是错误的。

function countTheObjects (arr) { let count = 0; for (let i = 0; i < arr.length; i++) { if (typeof arr[i] === 'object' && arr[i] !== null && !Array.isArray(arr[i]) ) { count++; } } return count; } 在Javascript中有let arr = [] console.log(typeof arr) // 'object' Array

如果您想确保不计算数组,请使用typeof。您还可以使用'object'代替Array.isArray(arr)来充分简化代码:

&#13;
&#13;
instanceof
&#13;
&#13;
&#13;

答案 2 :(得分:0)

  • 当元素为null时,您无需减少计数。
  • 检查!== null && typeof === "object"
  • null是一个基元,但在Javascript typeof null === 'object'

function countTheObjects(arr) {
  let count = 0;

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

console.log(countTheObjects([5, null, {}, "", null, {}, ""]));

使用ES6中的reduce功能:

function countTheObjects(arr) {
  return arr.reduce((count, obj) => count + (obj !== null && typeof obj === 'object'), 0);
}

console.log(countTheObjects([null, {}, 5, "", null, {}, ""]));

答案 3 :(得分:0)

你也可以这样做

var input = [
  [1, 2, 3], {
    key: 'some value'
  },
  null, null, 5, 6, null, {}
];

console.log(input.reduce((prev, current) => {
  return current !== null ? prev + 1 : prev
}, 0));

答案 4 :(得分:0)

这是一个简单的实现:

&#13;
&#13;
let dataArray = [1, {}, [], null, null, 'foo', 3, 4, 5, {}, {}, {}, 'foo']
let countNotNulls = arr => arr.filter( el => el !== null );
console.log(countNotNulls(dataArray).length);
&#13;
&#13;
&#13;

答案 5 :(得分:0)

A reliable approach for answering the OP's question boils down to ... just find or implement the correct/matching type detection method. Then, make use of this method as callback function of the filter method that filters the provided array of different/mixed types. Read the length property of the filtered result.

A generic implementation of an isObject check might look like this ...

function isObject(type) {
  return (!!type && (typeof type === 'object'));
};

... but it will let pass any value/type that neither is null nor undefined nor of any other primitive type. Thus it will also let pass other objects like instances of Array, RegExp, Date etc.

The OP wants to test for direct instances of Object. A solution then might look like the following provided ...

function isObjectObject(type) {
  return (/^\[object\s+Object\]$/).test(Object.prototype.toString.call(type));
}

function getObjectCount(list) {
  return Array.from(list).filter(isObjectObject).length;
}

console.log("(getObjectCount([]) === 0) ? ", (getObjectCount([]) === 0));
console.log("(getObjectCount([1, 3, 4, 5]) === 0) ? ", (getObjectCount([1, 3, 4, 5]) === 0));
console.log("(getObjectCount([1, 3, 4, 5, 'foo']) === 0) ? ", (getObjectCount([1, 3, 4, 5, 'foo']) === 0));
console.log("(getObjectCount([1, 3, 4, 5, {}, {}, {}, 'foo']) === 3) ? ", (getObjectCount([1, 3, 4, 5, {}, {}, {}, 'foo']) === 3));
console.log("(getObjectCount([1, [], 3, 4, 5, {}, {}, {}, 'foo']) === 3) ? ", (getObjectCount([1, [], 3, 4, 5, {}, {}, {}, 'foo']) === 3));
console.log("(getObjectCount([1, [], null, 3, 4, 5, {}, {}, {}, 'foo']) === 3) ? ", (getObjectCount([1, [], null, 3, 4, 5, {}, {}, {}, 'foo']) === 3));
console.log("(getObjectCount([1, {}, [], null, null, 'foo', 3, 4, 5, {}, {}, {}, 'foo']) === 4) ? ", (getObjectCount([1, {}, [], null, null, 'foo', 3, 4, 5, {}, {}, {}, 'foo']) === 4));
.as-console-wrapper { max-height: 100%!important; top: 0; }

答案 6 :(得分:-2)

你正在做不必要的减量。您应该将null检查移动到第一个if。 typeof []也是&#39; object&#39;

ffmpeg -y -i input -c:v libx264 -crf 20 output.mkv