简体   繁体   中英

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

I have the following AJAX call:

$('#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:

{
  "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.

I am confused at this point: is not .length the right way to check whether an array is empty or not in 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.

You can use Object.keys(data.result.error).length to see if it has any own, enumerable properties, which your example will have.

Eg, assuming data.result really points to that data structure, then:

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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