Cannot read properties of undefined reading length ошибка

Пытаюсь настроить выгрузку банковских выписок из почты в гугл таблицы.
При выполнении скрипта, прога ругается и выдает ошибку:

TypeError: Cannot read properties of undefined (reading 'length')
appendData_	@ json.gs:30
saveEmails	@ json.gs:36

на этот кусок кода:

function appendData_(sheet, array2d) {
    sheet.getRange(sheet.getLastRow() + 1, 1, array2d.length, array2d[0].length).setValues(array2d);
}

function saveEmails() {
    var array2d = processEmails();
    if (array2d) {

В чем может быть причина и как исправить?


  • Вопрос задан

  • 3549 просмотров

Ошибка «TypeError: Cannot read properties of undefined (reading ‘length’)» означает, что переменная «array2d» не определена или имеет значение «undefined», когда вызывается свойство «length» у массива. Это может произойти, если функция «processEmails()» не возвращает массив, либо возвращает пустой массив.

Чтобы исправить ошибку, необходимо проверить, что функция «processEmails()» возвращает массив с данными, а не «undefined» или пустой массив. Можно добавить проверку на «undefined» перед вызовом функции или добавить условие для обработки пустого массива.

Пригласить эксперта


  • Показать ещё
    Загружается…

21 сент. 2023, в 11:48

25000 руб./за проект

21 сент. 2023, в 11:40

10000 руб./за проект

21 сент. 2023, в 11:34

5000 руб./за проект

Минуточку внимания

One of the most common errors we record, “Cannot read properties of undefined (reading ‘length’)”, turned up in our own logs recently while looking into an issue with Microsoft Edge and the Facebook sdk. Let’s dive into this error, what it means, and how to fix it.

Breaking down the Message

TypeError: Cannot read properties of undefined (reading 'length')

In older browsers, this might also be shown as:

Cannot read property 'length' of undefined

TypeError is a subset of JavaScript Error that is thrown when code attempts to do something that does not exist on the target object.

This message indicates that our code expects to have an object with a length property, but that object was not present. length is commonly used on string and array, but a custom object could also have this property.

This is a blocking error, and script execution will stop when this error occurs.

Understanding the Root Cause

This error can be thrown for a lot of reasons, as it is incredibly common to reference the length property of string or array during everyday development. For example, if we had a function that acts on a string argument, but is called without a string, we would see this error.

function foo(myString) {
  if (myString.length >= 10) {
    // do something
  }
}

foo(); // Whoops! TypeError
undefined passed to string function

In our case, we were intercepting a call to fetch, and we had assumed the url property would be a string.

But, dear developer, it was not always a string. 🤦‍♂️.

We had some code like this that intercepted fetch requests and recorded some metadata if the request was correct. It looked something like this:

ourInterceptedFetch(options) {
  if (options.url.length <= 0) {
    // fail out
  }
}
Defensive checking a string

We were doing appropriate defensive type checking to make sure that the options argument had a valid url property. Unfortunately, fetch also accepts options to be any object with a stringifier: an object with a toString method. Like this:

fetch({
  toString: function() {
    return `https://whatever.com/`;
  }
});
Serializable object passed to fetch

In this case, options.url is undefined, so when we try to check options.url.length, it blows up with our error, “Cannot read property ‘length’ of undefined”. Ugh.

While this may be valid, it is a bit weird, right? We thought so too.

How to Fix It

So how do we fix this and prevent it from happening again?

1. Understand why your object is undefined

Understand why your object is undefined

First and foremost, you need to understand why this happened before you can fix it. You are probably not doing exactly the same thing we are, so the reason your object is undefined may be somewhat different. Consider:

  • Are you relying on a network response to be a certain shape?
  • Are you processing user-input?
  • Is an external function or library calling into your code?

Or maybe its just a logical bug somewhere in your code.

2. Add Defensive Checking

Add Defensive Checking

Anytime you don’t completely control the input into your code, you need to be defensively checking that arguments have the correct shape. API response change, functions get updated, and users do terrible, terrible things.

For instance, if you have a fetch request that receives a JSON response with a foo string property, you might have a defensive check that looks like this:

fetch("https://example.com/api")
  .then(resp => {
    return resp.json();
  })
  .then(json => {
    if (!json || typeof json.foo != 'string') {
      // Record an error, the payload is not the expected shape.
    }
  });
Defensive checking a fetch response

3. Monitor Your Environment

 Monitor Your Environment

You’ll need to make sure that the issue is really fixed and that the problem stops happening. Mistakes happen, APIs change, and users are unpredictable. Just because your application works today, doesn’t mean an error won’t be discovered tomorrow. Tracking when exceptional events happen to your users gives you the context to understand and fix bugs faster. Check out TrackJS Error Monitoring for the fastest and easiest way to get started.

The other answers are focusing on prop.items list but in your question you mention that you get the exception when trying to access the length of the places inside users.

You are getting the error message because some users may not have any places listed inside them, hence, no places list -> no length property.

To fix this, you need to check if the places list exists and then access its length:

placeCount={ user.places ? user.places.length : 0 }

Here, we use a ternary operator to check if user.places exists, then we use the length, else use zero.

Edit:
As pointed out by Phil in the comments below, you can also use coalescing operator, which is much cleaner, like this:

placeCount={ user.places?.length ?? 0 }

The syntax simply translates as if user.places has a value for length, then use that value, else use zero as a default value.

Are you experiencing the “cannot read property ‘length’ of undefined” error in JavaScript? This error occurs when you attempt to access the length property from a variable that has a value of undefined.

const arr = undefined;

// TypeError: Cannot read properties of undefined (reading 'length')
const length = arr.length;

console.log(length);

To fix the “cannot read property ‘length’ of undefined” error, perform an undefined check on the variable before accessing the length property from it. There are various ways to do this.

Surfshark VPN: Your ultimate cyber shield

Morning Brew logo

Protecting your connection is key. Surfing the web, you’re exposed to many risks: data breaches, hacking attacks, &
snoopers. One solution to fight them all — a VPN.

1. Use an if Statement

We can use an if statement to check if the variable is truthy before accessing the length property:

const arr = undefined;

let arrLength = undefined;

// Check if "arr" is truthy
if (arr) {
  arrLength = arr.length;
}

console.log(arrLength); // undefined


const str = undefined;

let strLength = undefined;

// Check if "str" is truthy
if (str) {
  strLength = str.length;
}

console.log(strLength); // undefined

2. Use Optional Chaining

We can use the optional chaining operator (?.) to return undefined and prevent the method call if the variable is nullish (null or undefined):

const arr = undefined;

// Use optional chaining on "arr" variable
const arrLength = arr?.length;

console.log(arrLength); // undefined


const str = undefined;

// Use optional chaining on "str" variable
const strLength = str?.length;

console.log(strLength); // undefined

3. Access the length Property of a Fallback Value

We can use the nullish coalescing operator (??) to provide a fallback value to access the length property from.

const arr = undefined;

// Providing an empty array fallback
const arrLength = (arr ?? []).length;

console.log(arrLength); // 0


const str = undefined;

// Providing an empty string fallback
const strLength = (str ?? '').length;

console.log(strLength); // 0

The nullish coalescing operator (??) returns the value to its left if it is not null or undefined. If it is, then ?? returns the value to its right.

console.log(2 ?? 5); // 2
console.log(undefined ?? 5); // 5

We can also use the logical OR (||) operator to provide a fallback value from which to access the length property.

const arr = undefined;

// Providing an empty array fallback
const arrLength = (arr || []).length;

console.log(arrLength); // 0

const str = undefined;

// Providing an empty string fallback
const strLength = (str || '').length;

console.log(strLength); // 0

Like the ?? operator, || returns the value to its left if it is not null or undefined. If it is, then || returns the value to its right.

4. Use a Fallback Value Instead of Accessing the length Property

We can also combine the optional chaining operator (?.) and the nullish coalescing operator (??) to provide a fallback value to use as the result, instead of accessing the length property from the undefined value.

const arr = undefined;

// Using "0" as a fallback value
const arrLength = arr?.length ?? 0;

console.log(arrLength); // 0


const str = undefined;

// Using "0" as a fallback value
const strLength = str?.length ?? 0;

console.log(strLength); // 0

As we saw earlier, the logical OR operator (||) can replace the ?? operator in cases like this:

const arr = undefined;

// Using "0" as a fallback value
const arrLength = arr?.length || 0;

console.log(arrLength); // 0

const str = undefined;

// Using "0" as a fallback value
const strLength = str?.length || 0;

console.log(strLength); // 0

Every Crazy Thing JavaScript Does

A captivating guide to the subtle caveats and lesser-known parts of JavaScript.

Every Crazy Thing JavaScript Does

Sign up and receive a free copy immediately.

В процессе программирования мы часто сталкиваемся с различными ошибками в своих скриптах. Одна из самых распространенных ошибок, с которой можно столкнуться при работе с JavaScript, — это ошибка, связанная с невозможностью чтения свойства «length» неопределенного объекта. Эта ошибка может произойти в разных ситуациях и может быть вызвана многими факторами. В этой статье мы разберем, как исправить ошибку в скрипте: «Cannot read properties of undefined (reading ‘length’)?».

Что такое ошибка «Cannot read properties of undefined (reading ‘length’)?»

Прежде чем мы начнем рассматривать способы исправления этой ошибки, давайте поподробнее разберем, что она означает. При попытке выполнения действия чтения свойства «length» неопределенного объекта, JavaScript выдает ошибку, сообщая, что это свойство не определено. В консоли может появиться следующее сообщение об ошибке:

Uncaught TypeError: Cannot read properties of undefined (reading ‘length’)

Здесь «uncaught TypeError» означает, что произошла ошибка типа, и сообщает о том, что свойство не определено и поэтому не может быть прочитано.

В чем причина ошибки «Cannot read properties of undefined (reading ‘length’)?»

Самая распространенная причина появления этой ошибки — попытка чтения свойства «length» у неопределенного объекта. Это может произойти, когда объект, который вы пытаетесь использовать, не существует, или когда он не определен. Эта ошибка может возникнуть из-за различных причин, таких как:

— Отсутствие инициализации объекта
— Передача пустого значения в функцию
— Ошибки в синтаксисе кода или неправильное использование методов и объектов
— Неправильная обработка ответов сервера или ошибки при взаимодействии с API

Как исправить ошибку «Cannot read properties of undefined (reading ‘length’)?»

Вот несколько способов, которые позволят исправить или избежать ошибки «Cannot read properties of undefined (reading ‘length’)?»:

1. Проверка объекта на определенность

Перед тем, как читать свойства объекта, необходимо проверить, существует ли объект и определен ли он. Для этого можно использовать метод typeof в JavaScript. Этот метод возвращает строку с типом значения, переданного в параметре. Если объект определен, его тип должен быть «Object», если его нет, тип будет «undefined». Пример:

if (typeof myObject !== ‘undefined’ && myObject.length > 0) {
// Тут код, который обрабатывает объект
}

2. Проверка на пустой объект

Читать свойства объекта без проверки на его заполненность – это классический способ вызвать ошибку чтения свойства «length» объекта, который не содержит данных. Чтобы избежать этой ошибки, надо проверять объект на наличие его свойств. Пример:

if (typeof myObject !== ‘undefined’ && myObject !== null && Object.keys(myObject).length > 0) {
// Тут код, который обрабатывает объект
}

3. Проверка на typeof null

Когда возникает ошибка «Cannot read properties of undefined (reading ‘length’)», необходимо проверить, не является ли объект, вызывающий ошибку, null. Это может произойти, когда параметр, переданный в функцию, имеет значение null. Объект null не имеет методов или свойств, и поэтому вызов метода объекта null приводит к ошибке. Пример:

if (typeof myObject !== ‘undefined’ && myObject !== null && myObject.length > 0) {
// Тут код, который обрабатывает объект
}

4. Проверка на наличие переменной

Кроме того, перед чтением свойства объекта следует проверить, определена ли переменная. Если переменная не определена, вызов метода объекта приведет к ошибке. Пример:

if (typeof myObject === ‘undefined’) {
var myObject = {};
}

5. Ошибка try-catch

Если все прочие способы не помогли, то можно использовать конструкцию try-catch. В этом случае, вместо того, чтобы предотвратить ошибку, мы ее перехватываем и обрабатываем. Пример:

try {
if(myObject.length>0){
// Код, который обрабатывает объект
}
} catch(e) {
console.log(‘Ошибка:’, e.message);
}

Как правило, эти способы помогают избежать ошибки «Cannot read properties of undefined (reading ‘length’)?» при работе с JavaScript.

Заключение

Ошибки являются неизбежной частью программирования, и при их возникновении нужно обладать достаточными знаниями и навыками, чтобы быстро исправить ошибку и продолжить работу. Ошибка «Cannot read properties of undefined (reading ‘length’)» свидетельствует о недоступности какого-то свойства объекта, и в большинстве случаев ее возникновение может быть предотвращено. Определять и устранять эту ошибку можно разными способами, и выбор определенной стратегии зависит от конкретной ситуации. Но в любом случае, знание возможных причин ошибки и навыки отладки кода помогут вам быстро и эффективно ее исправить.

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Cannot read properties of null reading classlist ошибка
  • Cannot read from port ошибка miflash
  • Cannot open output file ошибка
  • Cannot load nvml ошибка
  • Cannot invoke method on null object groovy ошибка

  • Добавить комментарий

    ;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: