目录
Cannot read property ‘includes’ of Undefined in JavaScript
无法读取未定义的属性(读取 ‘includes’)
includes()
在值上调用方法时发生“无法读取未定义的属性(读取‘包含’)”错误undefined
。
要解决该错误,请确保仅在实现它的数据类型(数组和字符串)上调用该方法。
下面是错误如何发生的示例。
const arr = undefined; // ⛔️ TypeError: Cannot read properties of undefined (reading 'includes') arr.includes('example'); const str = undefined; // ⛔ TypeError: Cannot read properties of undefined (reading 'includes') str.includes('example');
我们试图在导致错误的值includes()
上调用该方法。undefined
将变量初始化为空数组或空字符串
解决该错误的一种方法是使用逻辑或 (||) 运算符将变量初始化为空数组或空字符串。
const fromDb = undefined; // ✅ Using Array.includes() const arr = fromDb || []; const result1 = arr.includes('abc'); console.log(result1); // 👉️ false // ------------------------------------ // ✅ Using String.includes() const str = fromDb || ''; const result2 = str.includes('abc'); console.log(result2); // 👉️ false
如果左边的值是假的(例如 ),逻辑 OR (||) 运算符返回右边的值undefined
。
您还可以在调用该方法之前立即提供空数组或空字符串的回退includes()
。
// ✅ Using Array.includes() const arr = undefined; const result1 = (arr || []).includes('abc'); console.log(result1); // 👉️ false // ------------------------------------ // ✅ Using String.includes() const str = undefined; const result2 = (str || '').includes('abc'); console.log(result2); // 👉️ false
如果arr
变量存储的是假值(例如undefined
),则表达式将调用includes()
空数组上的方法。
使用可选链 (?.) 解决错误
如果引用为空,您还可以使用可选的链接运算符进行短路。
// ✅ Using Array.includes() const arr = undefined; const result1 = arr?.includes('abc') || false; console.log(result1); // 👉️ false // ------------------------------------ // ✅ Using String.includes() const str = undefined; const result2 = str?.includes('abc') || false; console.log(result2); // 👉️ false
如果左侧的值为空值(或) ,则可选链接(?.)运算符会短路,而不是抛出错误。undefined
null
在调用之前检查值的类型是否正确includes()
您可以使用该Array.isArray
方法检查值是否为数组,并使用
typeof
运算符
检查变量是否存储字符串。
// ✅ Using Array.includes() const arr = undefined; if (Array.isArray(arr)) { const result = arr.includes('abc'); console.log(result); } else { console.log('The value is NOT an array'); } // ------------------------------------ // ✅ Using String.includes() const str = undefined; if (typeof str === 'string') { const result = str.includes('abc'); console.log(result); } else { console.log('The value is NOT a string'); }
在第一个示例中,if
仅当变量存储数组时才运行块,否则else
运行块。
在第二个示例中,该if
块仅在变量存储字符串时运行。
使用三元运算符解决错误
您也可以使用三元运算符来解决错误。
// ✅ Using Array.includes() const arr = undefined; const result1 = Array.isArray(arr) ? arr.includes('abc') : false; console.log(result1); // 👉️ false // -------------------------------------------------------- // ✅ Using String.includes() const str = undefined; const result2 = typeof str === 'string' ? str.includes('abc') : false; console.log(result2); // 👉️ false
The ternary operator is
very similar to an if/else
statement.
If the expression before the question mark evaluates to a truthy value, the
value to the left of the colon is returned, otherwise the value to the right of
the colon is returned.
If the value stored in the arr
variable is falsy (e.g. undefined
), we return
an empty array, otherwise, we return the result of calling the includes
method.
# Track down where the variable got assigned an undefined
value
If the error persists, you have to track down where the variable got assigned an
undefined
value.
The includes
method exists on arrays and strings, so trying to call it on a
value of any other type causes an error.
undefined
values is assigning the output of a function that doesn’t return anything to a variable.Many built-in methods that mutate an object in place return undefined
.
All JavaScript functions that don’t return a value return undefined
.
# Cannot read properties of null (reading ‘includes’) in JS
The “Cannot read properties of null (reading ‘includes’)” error occurs when
the includes()
method is called on a variable that stores a null
value.
To solve the error, make sure to only call the method on the correct data
type – array or string.
Here is an example of how the error occurs.
const arr = null; // ⛔️ TypeError: Cannot read properties of null (reading 'includes') console.log(arr.includes('test'));
We attempted to call the includes()
method on a null
value which caused the
error.
# Initialize the variable to an empty array or empty string
One way to solve the error is to use the logical OR (||) operator to initialize
the variable to an empty array or an empty string.
const fromDb = null; // ✅ Using Array.includes() const arr = fromDb || []; const result1 = arr.includes('abc'); console.log(result1); // 👉️ false // ------------------------------------ // ✅ Using String.includes() const str = fromDb || ''; const result2 = str.includes('abc'); console.log(result2); // 👉️ false
The logical OR (||) operator returns the
value to the right if the value to the left is falsy (e.g. null
).
You can also provide a fallback of an empty array or empty string right before
calling the includes()
method.
// ✅ Using Array.includes() const arr = null; const result1 = (arr || []).includes('abc'); console.log(result1); // 👉️ false // ------------------------------------ // ✅ Using String.includes() const str = null; const result2 = (str || '').includes('abc'); console.log(result2); // 👉️ false
If the arr
variable stores a falsy value (e.g. null
), the expression calls
the includes()
method on an empty array.
# Using optional chaining (?.) to solve the error
You can also use the optional chaining operator to short-circuit if the
reference is nullish.
// ✅ Using Array.includes() const arr = null; const result1 = arr?.includes('abc') || false; console.log(result1); // 👉️ false // ------------------------------------ // ✅ Using String.includes() const str = null; const result2 = str?.includes('abc') || false; console.log(result2); // 👉️ false
The optional chaining (?.) operator
short-circuits, instead of throwing an error, if the value on the left is
nullish (null
or undefined
).
# Check if the value is of the correct type before calling includes()
You can use the Array.isArray
method to check if a value is an array and the
typeof
operator to check if a variable stores a string.
// ✅ Using Array.includes() const arr = null; if (Array.isArray(arr)) { const result = arr.includes('abc'); console.log(result); } else { console.log('The value is NOT an array'); } // ------------------------------------ // ✅ Using String.includes() const str = null; if (typeof str === 'string') { const result = str.includes('abc'); console.log(result); } else { console.log('The value is NOT a string'); }
In the first example, the if
block is only run if the variable stores an
array, otherwise, the else
block runs.
In the second example, the if
block only runs if the variable stores a string.
# Use the ternary operator to solve the error
You can also use the ternary operator to solve the error.
// ✅ Using Array.includes() const arr = null; const result1 = Array.isArray(arr) ? arr.includes('abc') : false; console.log(result1); // 👉️ false // -------------------------------------------------------- // ✅ Using String.includes() const str = null; const result2 = typeof str === 'string' ? str.includes('abc') : false; console.log(result2); // 👉️ false
三元运算符与语句非常相似if/else
。
如果问号前的表达式的计算结果为真值,则返回冒号左侧的值,否则返回冒号右侧的值。
如果存储在变量中的值arr
是假的(例如null
),我们返回一个空数组,否则,我们返回调用该方法的结果includes
。