简体   繁体   English

无法将 null 分配给变量

[英]Cannot assign null to a variable

 const letsMatch = (string, char) => { const newRegex = new RegExp(char, "gi"); let result = string.match(newRegex); const findNegIndex = result.indexOf(char); if (findNegIndex === null) { return result = 0; } else { if (result.length === 2) { const findFirstIndex = fiveT.indexOf(char); const findSecondIndex = fiveT.indexOf(char, findFirstIndex + 1); result = findSecondIndex - findFirstIndex + 2; return result; } else { return (result = 0); } } } console.log(letsMatch('totititiTo', 'r'))

line 4: const findNegIndex = result.indexOf(char);第 4 行: const findNegIndex = result.indexOf(char); Throws Uncaught TypeError: Cannot read properties of null (reading 'indexOf').引发未捕获的类型错误:无法读取 null 的属性(读取“indexOf”)。

According to the documentation , String.prototype.match() will return null ( not an empty array) when no matches are found.根据文档,当找不到匹配项时, String.prototype.match()将返回null不是空数组)。

And no matches are found.并且找不到匹配项。

You can default to an empty array when it returns null :当它返回null时,您可以默认为空数组:

 const letsMatch = (string, char) => { const newRegex = new RegExp(char, "gi"); let result = string.match(newRegex) || []; // here const findNegIndex = result.indexOf(char); if (findNegIndex === null) { return result = 0; } else { if (result.length === 2) { const findFirstIndex = fiveT.indexOf(char); const findSecondIndex = fiveT.indexOf(char, findFirstIndex + 1); result = findSecondIndex - findFirstIndex + 2; return result; } else { return (result = 0); } } } console.log(letsMatch('totititiTo', 'r'))

(As an aside, it's not really clear what this function is meant to accomplish, or what you expect return result = 0 to mean other than return 0 . But at the very least the error is because you're assuming string.match will always return an array, and there exists a use case where it does not.) (顺便说一句,目前还不清楚这个 function 的目的是什么,或者你期望return result = 0意味着什么而不是return 0 。但至少错误是因为你假设string.match总是返回一个数组,并且存在一个不存在的用例。)

Depending on what you're coding in...取决于你在编码...

Use?.利用?。 - it'll return undefined if result doesn't have that property, and the || - 如果结果没有该属性,它将返回 undefined,并且 || will shunt it on over to the null const findNegIndex = result?.indexOf(char) || null;将它分流到 null const findNegIndex = result?.indexOf(char) || null; const findNegIndex = result?.indexOf(char) || null;

or或者

const findNegIndex = result? result.indexOf(char): null;

I'd also shy away from a variable named "string", for readability's sake - since String.match为了便于阅读,我也会回避一个名为“string”的变量——因为 String.match

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

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