javascript 检测数组中是否只有空值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19337761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:13:58  来源:igfitidea点击:

Detect if array has only null values in it

javascript

提问by Discipol

I have an array and I would like a simple non-loop test if that arrays contains ONLY nullvalues. Empty array also counts as having only null values.

我有一个数组,如果该数组只包含null值,我想要一个简单的非循环测试。空数组也算作只有空值。

I guess another way to describe the issue is to test if the array has at least one non-null value.

我想描述这个问题的另一种方法是测试数组是否至少有一个非空值。

So:

所以:

Good: [ null, null, null ]
Good: []
Bad:  [ null, 3, null ]

回答by Felix Kling

You can avoid using an explicitloop by using Array#every:

您可以通过使用以下命令来避免使用显式循环Array#every

var all_null = arr.every(function(v) { return v === null; });

but of course internally the engine will still iterate over the array. Iterating over the array explicitly might actually be faster. The important thing to do is breakout of the loop once you encounter an element which is not null(the method does that).

但当然在内部引擎仍然会遍历数组。显式迭代数组实际上可能更快。重要的事情是一旦遇到一个不是的元素(该方法会这样做)就跳出循环null

This method is not supported in every browser, see the link for a polyfill.

并非所有浏览器都支持此方法,请参阅 polyfill 的链接。

回答by David says reinstate Monica

The easiest way I can think of is a simple:

我能想到的最简单的方法很简单:

Array.prototype.isNull = function (){
    return this.join().replace(/,/g,'').length === 0;
};

[null, null, null].isNull(); // true
[null, 3, null].isNull(); // false

JS Fiddle demo.

JS小提琴演示

This takes the array, joins the elements of that array together (without arguments join()joins the array elements together with ,characters) to return a string, replaces all the ,characters in that string (using a regular expression) with empty strings and then tests if the length is equal to 0. So:

这需要数组,将该数组的元素连接在一起(没有参数join()将数组元素与,字符连接在一起)以返回一个字符串,将该字符串中的所有,字符(使用正则表达式)替换为空字符串,然后测试长度等于0。所以:

[null, 3, null].isNull()

Joined together to give:

联合起来给予:

',3,'

Has all the commas replaced (using the gflag after the regular expression), to give:

已替换所有逗号(使用g正则表达式后的标志),以给出:

'3'

Tested to see if its length is equal to 0, to give:

测试它的长度是否等于0,给出:

false

It's worth noting that there is the problem of, potentially, the ,featuring in the checked arrays.

值得注意的是,,检查数组中可能存在特征问题。

Also, Felix Kling's answerissomewhat faster.

此外,菲利克斯克林的回答稍快

回答by thefourtheye

var arrayData1 = [null, null, null];
var arrayData2 = [];
var arrayData3 = [null, 3, null];
var arrayData4 = [3];

function isNull(inputArray) {
    if (inputArray.length) {
        var currentElement = inputArray[0];
        for (var i = 1, len = inputArray.length; i < len && currentElement === null; i += 1) {
            currentElement = currentElement || inputArray[i];
        }
        if (currentElement !== null) {
            return false;
        }
    }
    return true;
}

console.log(isNull(arrayData1));
console.log(isNull(arrayData2));
console.log(isNull(arrayData3));
console.log(isNull(arrayData4));

Output

输出

true
true
false
false

Edit 1:And here comes the most efficient solution (suggested by user2736012). This solution applies KISSprinciple. Keep It Simple, Silly.

编辑 1:这是最有效的解决方案(由 user2736012 建议)。此解决方案应用KISS原理。ķEEP牛逼小号imple,Ş意利。

function isNull(inputArray) {
  for (var i = 0, len = inputArray.length; i < len; i += 1)
    if (inputArray[i] !== null)
      return false;
  return true;
}

Performance Result: http://jsperf.com/so-q-19337761/6

性能结果:http: //jsperf.com/so-q-19337761/6