最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Trying to find if array is full or not - Stack Overflow

programmeradmin0浏览0评论

I'm working with JQuery to determine if an array, built earlier, with a determined number of indexes, is full or not. When created, array looks like this :

,,,,,,

All I want to do is find if every position is filled or not.

So bascially, i'm trying to test if and only if

[x,x,x,x,x,x]

For example, if

[x,x,x,,x,x]  or if [x,,,,,] //return false, wrong...

Thanks a lot.

I'm working with JQuery to determine if an array, built earlier, with a determined number of indexes, is full or not. When created, array looks like this :

,,,,,,

All I want to do is find if every position is filled or not.

So bascially, i'm trying to test if and only if

[x,x,x,x,x,x]

For example, if

[x,x,x,,x,x]  or if [x,,,,,] //return false, wrong...

Thanks a lot.

Share Improve this question edited Feb 10, 2010 at 15:52 pixelboy asked Feb 10, 2010 at 15:34 pixelboypixelboy 7291 gold badge13 silver badges37 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

You don't need any specific jQuery stuff to read the size of an array. Just vanilla javascript has what you need.

var arrayMaxValues = 4;
var testArray = [1,2,3,4];

if ( testArray.length == arrayMaxValues )
{
  alert( 'Array is full!' );
}
else if ( testArray.length > arrayMaxValues )
{
  alert( 'Array is overstuffed!' );
} else {
  alert( 'There's plenty of room!' );
}

EDIT

Ah, you re-typed your question. So, you want to see if they array has zero null or undefined values?

function isArrayFull( arr )
{
  for ( var i = 0, l = arr.length; i < l; i++ )
  {
    if ( 'undefined' == typeof arr[i] || null === arr[i] )
    {
      return false
    }
  }
  return true;
}

If you fill your initial array with nulls, like:

const arr = Array(9).fill(null);

Then you can use some() or every() like this:

// check if a null doesn't exist
!arr.some(element => element === null)

// check if every element is not null
arr.every(element => element !== null)

Use whichever you like, since both of them breaks the loop when a null is found.

I know this is doing the same as Peter Bailey's function, but I only wanted to share it since it's a different approach using the built-in power of array filtering.

So, since the full array has a predetermined length you could filter it against 'undefined' and null and pare lengths, like this:

function isArrayFull(arr) {
   return arr.length === arr.filter(function(o) {
     return typeof o !== 'undefined' ||  o !== null;
   }).length;
}
发布评论

评论列表(0)

  1. 暂无评论