Javascript 检查 React Native 中的数组是否为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43869197/
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
Check if an array is empty in React Native
提问by Proz1g
How can I check if an array is empty with a IF statment?
如何使用 IF 语句检查数组是否为空?
I have this array 'acessos' that's empty
我有这个空的数组“accessos”
...
constructor(props){
super(props);
this.state = {
acessos:[]
};
}
...
Then I'm trying to check if 'acessos' is empty and if it is I push some data in it. I've tried with null but with no results, so how can I check if is empty?
然后我试图检查“acessos”是否为空,如果是,我将一些数据放入其中。我试过 null 但没有结果,那么如何检查是否为空?
...
if(this.state.acessos === null){
this.state.acessos.push({'uuid': beacons.uuid, 'date':date});
this.setState({acessos: this.state.acessos});
} else {
...
回答by atitpatel
I agree to Julien. Also you don't have to compare it to null. You can write it like
我同意朱利安。此外,您不必将其与 null 进行比较。你可以这样写
this.state.acessos && this.state.acessos.length > 0
回答by oma
Just check if your array exists and has a length:
只需检查您的数组是否存在并具有长度:
if (this.state.acessos && this.state.acessos.length) {
//your code here
}
No need to check this.state.acessos.length > 0. 0is falsy anyway, a small performance improvement.
无需检查this.state.acessos.length > 0。0无论如何都是假的,一个小的性能改进。
You can found a performance test regarding 'array.length' vs 'array.length > 0' here: https://jsperf.com/test-of-array-length
您可以在此处找到有关“array.length”与“array.length > 0”的性能测试:https: //jsperf.com/test-of-array-length
回答by Philip John
You need not even check for the length since ECMAScript 5.1 You can simply write the same condition as follows.
从 ECMAScript 5.1 开始,您甚至不需要检查长度您可以简单地编写如下相同的条件。
this.state.acessos && this.state.acessos.length
By default this.state.acessos.lengthchecks if the length is NOT undefined or null or zero.
默认情况下this.state.acessos.length检查长度是否未定义或为空或零。

