简体   繁体   English

.length是否不是检查Javascript中数组是否为空的正确方法?

[英]Is not `.length` the right way to check whether an array is empty or not in Javascript?

I have the following AJAX call: 我有以下AJAX呼叫:

$('#fileupload').show().fileupload({
    url: '/upload',
    type: "POST",
    cache: false,
    dataType: 'json',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    done: function (e, data) {
        var error_msg = $("#load_error_msg");

        error_msg.html('');

        if (data.result.error.length > 0) {
            // process errors messages here 
        } else {
            // do something else
        }
    },
})

The upload method on the backend return a JSON like the following: 后端的upload方法返回一个JSON,如下所示:

{
  "error": {
    "fileUploadErrorIniSize": "File '' exceeds the defined ini size"
  }
}

The code is bypassing this checking data.result.error.length and going always trough the else condition. 代码将绕过此检查data.result.error.length并始终通过else条件。

I am confused at this point: is not .length the right way to check whether an array is empty or not in Javascript? 我在这一点上感到困惑: .length不是检查Javascript中数组是否为空的正确方法吗? If it's not which is the right way? 如果不是,那是正确的方法?

It's not an array, it's a plain object. 它不是数组,而是一个普通对象。 Plain objects don't have a length property by default. 普通对象默认情况下没有length属性。

You can use Object.keys(data.result.error).length to see if it has any own, enumerable properties, which your example will have. 您可以使用Object.keys(data.result.error).length来查看它是否具有自己的示例性实例可枚举的属性。

Eg, assuming data.result really points to that data structure, then: 例如,假设data.result确实指向该数据结构,则:

if (Object.keys(data.result.error).length > 0) {

If there's any possibility that data.result won't have an error property at all, you'll want to guard against that: 如果有可能data.result根本没有error属性,则需要注意以下data.result

if (data.result.error && Object.keys(data.result.error).length > 0) {

But if you know it'll always be there (just sometimes empty), there's no need. 但是,如果您知道它会一直存在(有时只是空的),则没有必要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM