简体   繁体   English

为什么我无法读取未定义的属性“toString”

[英]Why do I get Cannot read property 'toString' of undefined

I use this package.我用这个包。 I've added these console.log 's at the beginning of the slug function.我在 slug 函数的开头添加了这些console.log

function slug(string, opts) {
    console.log('log 1: -------');
    console.log('log 2: ' + string);
    console.log('log 3: ' + typeof string);
    string = string.toString();
    ....
 }

Here is the output:这是输出:

log 1: -------
log 2: Yüzey Aktif Maddeler
log 3: string
/Users/------/seeder/node_modules/mongodb/lib/utils.js:99
    process.nextTick(function() { throw err; });
                                  ^

TypeError: Cannot read property 'toString' of undefined
    at slug (/Users/------/seeder/node_modules/slug/slug.js:16:20)
    at Object.createSlug (/Users/------/seeder/seeder/utils.js:4:9)
    at getContent (/Users/------/seeder/seeder/content-seeder.js:345:22)
    at topic.contents.forEach.content (/Users/------/seeder/seeder/content-seeder.js:425:31)
    at Array.forEach (native)
    at /Users/------/seeder/seeder/content-seeder.js:424:21
    at /Users/------/seeder/node_modules/mongodb/lib/collection.js:523:5
    at /Users/------/seeder/node_modules/mongodb/lib/collection.js:701:5
    at handleCallback (/Users/------/seeder/node_modules/mongodb/lib/utils.js:96:56)
    at executeCommands (/Users/------/seeder/node_modules/mongodb/lib/bulk/ordered.js:405:12)

Even if type of string parameter is a string, string.toString() throws a TypeError.即使字符串参数的类型是字符串, string.toString()抛出 TypeError。 It says string is undefined.它说字符串未定义。

I'm not an experienced js developer.我不是经验丰富的 js 开发人员。 Why would this happen?为什么会发生这种情况?

Edit: I call it from this function编辑:我从这个函数调用它

function getContent(content, categoryId) {
    console.log(content.topicVideo);
    return {
        // _id: Random.id(),
        // other properties
        contentSlug: slug(content.topicVideo.contentName, {
            lower: true
        })
    };
}

New logs:新日志:

{ id: '197505065',
  categorySort: 18,
  categoryName: 'Hayatımızda Kimya',
  contentSort: 2,
  contentName: 'Yüzey Aktif Maddeler',
  fileName: 'KonuAnlatimi.mp4' }

Edit:编辑:

I've added a log at the end of the slug function.我在 slug 函数的末尾添加了一个日志。

    console.log(result);
    return result;
};

This prints the results and then throws error.这会打印结果,然后抛出错误。

log 1: -------
log 2: Yüzey Aktif Maddeler
log 3: string
log 4: Yüzey Aktif Maddeler
yuzey-aktif-maddeler

Edit: I think this line gives a hint:编辑:我认为这一行给出了一个提示:

/Users/------/seeder/node_modules/mongodb/lib/utils.js:99
    process.nextTick(function() { throw err; });

I think it logs correct string, but fails on undefined one without logging the logs.我认为它记录了正确的字符串,但在未记录日志的情况下在未定义的字符串上失败。 Is this possible?这可能吗? I've found out that one of content.topicVideo.contentName is actually undefined.我发现 content.topicVideo.contentName 之一实际上是未定义的。 But error is thrown without logging it.但是不记录就抛出错误。 Is this even possible?这甚至可能吗?

To make sure that .toString() doesn't throw an error, you could:要确保 .toString() 不会引发错误,您可以:

string = "" + string; // amends the value to an string, even if its undefined or null etc

instead of:代替:

string = string.toString();

However you could also check if the value of string is undefined or null.但是,您也可以检查字符串的值是否为 undefined 或 null。 Also see here .另请参阅此处

Maybe you should check if string has a falsy value and(optionally if it is not a string)也许你应该检查字符串是否有一个假值(如果它不是一个字符串,则可选)

function slug(string, opts) {
    console.log('log 1: -------');
    console.log('log 2: ' + string);
    console.log('log 3: ' + typeof string);
    if(string)
        string = string.toString();
    ....
 }

From MDN:来自 MDN:

Falsy假的

A falsy value is a value that translates to false when evaluated in a Boolean context.假值是在布尔上下文中计算时转换为假的值。

More about falsy values in JavaScript here更多关于 JavaScript 中的假值在这里

The following code works fine (added slug.js module into the script to test).以下代码工作正常(将 slug.js 模块添加到脚本中进行测试)。 Perhaps this will help you analyze your code?也许这会帮助你分析你的代码?

 (function (root) { // lazy require symbols table var _symbols, removelist; function symbols(code) { if (_symbols) return _symbols[code]; _symbols = require('unicode/category/So'); removelist = ['sign','cross','of','symbol','staff','hand','black','white'] .map(function (word) {return new RegExp(word, 'gi')}); return _symbols[code]; } function slug(string, opts) { string = string.toString(); if ('string' === typeof opts) opts = {replacement:opts}; opts = opts || {}; opts.mode = opts.mode || slug.defaults.mode; var defaults = slug.defaults.modes[opts.mode]; var keys = ['replacement','multicharmap','charmap','remove','lower']; for (var key, i = 0, l = keys.length; i < l; i++) { key = keys[i]; opts[key] = (key in opts) ? opts[key] : defaults[key]; } if ('undefined' === typeof opts.symbols) opts.symbols = defaults.symbols; var lengths = []; for (var key in opts.multicharmap) { if (!opts.multicharmap.hasOwnProperty(key)) continue; var len = key.length; if (lengths.indexOf(len) === -1) lengths.push(len); } var code, unicode, result = ""; for (var char, i = 0, l = string.length; i < l; i++) { char = string[i]; if (!lengths.some(function (len) { var str = string.substr(i, len); if (opts.multicharmap[str]) { i += len - 1; char = opts.multicharmap[str]; return true; } else return false; })) { if (opts.charmap[char]) { char = opts.charmap[char]; code = char.charCodeAt(0); } else { code = string.charCodeAt(i); } if (opts.symbols && (unicode = symbols(code))) { char = unicode.name.toLowerCase(); for(var j = 0, rl = removelist.length; j < rl; j++) { char = char.replace(removelist[j], ''); } char = char.replace(/^\\s+|\\s+$/g, ''); } } char = char.replace(/[^\\w\\s\\-\\.\\_~]/g, ''); // allowed if (opts.remove) char = char.replace(opts.remove, ''); // add flavour result += char; } result = result.replace(/^\\s+|\\s+$/g, ''); // trim leading/trailing spaces result = result.replace(/[-\\s]+/g, opts.replacement); // convert spaces result = result.replace(opts.replacement+"$",''); // remove trailing separator if (opts.lower) result = result.toLowerCase(); return result; }; slug.defaults = { mode: 'pretty', }; slug.multicharmap = slug.defaults.multicharmap = { '<3': 'love', '&&': 'and', '||': 'or', 'w/': 'with', }; // https://code.djangoproject.com/browser/django/trunk/django/contrib/admin/media/js/urlify.js slug.charmap = slug.defaults.charmap = { // latin 'À': 'A', 'Á': 'A', 'Â': 'A', 'Ã': 'A', 'Ä': 'A', 'Å': 'A', 'Æ': 'AE', 'Ç': 'C', 'È': 'E', 'É': 'E', 'Ê': 'E', 'Ë': 'E', 'Ì': 'I', 'Í': 'I', 'Î': 'I', 'Ï': 'I', 'Ð': 'D', 'Ñ': 'N', 'Ò': 'O', 'Ó': 'O', 'Ô': 'O', 'Õ': 'O', 'Ö': 'O', 'Ő': 'O', 'Ø': 'O', 'Ù': 'U', 'Ú': 'U', 'Û': 'U', 'Ü': 'U', 'Ű': 'U', 'Ý': 'Y', 'Þ': 'TH', 'ß': 'ss', 'à':'a', 'á':'a', 'â': 'a', 'ã': 'a', 'ä': 'a', 'å': 'a', 'æ': 'ae', 'ç': 'c', 'è': 'e', 'é': 'e', 'ê': 'e', 'ë': 'e', 'ì': 'i', 'í': 'i', 'î': 'i', 'ï': 'i', 'ð': 'd', 'ñ': 'n', 'ò': 'o', 'ó': 'o', 'ô': 'o', 'õ': 'o', 'ö': 'o', 'ő': 'o', 'ø': 'o', 'ù': 'u', 'ú': 'u', 'û': 'u', 'ü': 'u', 'ű': 'u', 'ý': 'y', 'þ': 'th', 'ÿ': 'y', 'ẞ': 'SS', // greek 'α':'a', 'β':'b', 'γ':'g', 'δ':'d', 'ε':'e', 'ζ':'z', 'η':'h', 'θ':'8', 'ι':'i', 'κ':'k', 'λ':'l', 'μ':'m', 'ν':'n', 'ξ':'3', 'ο':'o', 'π':'p', 'ρ':'r', 'σ':'s', 'τ':'t', 'υ':'y', 'φ':'f', 'χ':'x', 'ψ':'ps', 'ω':'w', 'ά':'a', 'έ':'e', 'ί':'i', 'ό':'o', 'ύ':'y', 'ή':'h', 'ώ':'w', 'ς':'s', 'ϊ':'i', 'ΰ':'y', 'ϋ':'y', 'ΐ':'i', 'Α':'A', 'Β':'B', 'Γ':'G', 'Δ':'D', 'Ε':'E', 'Ζ':'Z', 'Η':'H', 'Θ':'8', 'Ι':'I', 'Κ':'K', 'Λ':'L', 'Μ':'M', 'Ν':'N', 'Ξ':'3', 'Ο':'O', 'Π':'P', 'Ρ':'R', 'Σ':'S', 'Τ':'T', 'Υ':'Y', 'Φ':'F', 'Χ':'X', 'Ψ':'PS', 'Ω':'W', 'Ά':'A', 'Έ':'E', 'Ί':'I', 'Ό':'O', 'Ύ':'Y', 'Ή':'H', 'Ώ':'W', 'Ϊ':'I', 'Ϋ':'Y', // turkish 'ş':'s', 'Ş':'S', 'ı':'i', 'İ':'I', 'ğ':'g', 'Ğ':'G', // russian 'а':'a', 'б':'b', 'в':'v', 'г':'g', 'д':'d', 'е':'e', 'ё':'yo', 'ж':'zh', 'з':'z', 'и':'i', 'й':'j', 'к':'k', 'л':'l', 'м':'m', 'н':'n', 'о':'o', 'п':'p', 'р':'r', 'с':'s', 'т':'t', 'у':'u', 'ф':'f', 'х':'h', 'ц':'c', 'ч':'ch', 'ш':'sh', 'щ':'sh', 'ъ':'u', 'ы':'y', 'ь':'', 'э':'e', 'ю':'yu', 'я':'ya', 'А':'A', 'Б':'B', 'В':'V', 'Г':'G', 'Д':'D', 'Е':'E', 'Ё':'Yo', 'Ж':'Zh', 'З':'Z', 'И':'I', 'Й':'J', 'К':'K', 'Л':'L', 'М':'M', 'Н':'N', 'О':'O', 'П':'P', 'Р':'R', 'С':'S', 'Т':'T', 'У':'U', 'Ф':'F', 'Х':'H', 'Ц':'C', 'Ч':'Ch', 'Ш':'Sh', 'Щ':'Sh', 'Ъ':'U', 'Ы':'Y', 'Ь':'', 'Э':'E', 'Ю':'Yu', 'Я':'Ya', // ukranian 'Є':'Ye', 'І':'I', 'Ї':'Yi', 'Ґ':'G', 'є':'ye', 'і':'i', 'ї':'yi', 'ґ':'g', // czech 'č':'c', 'ď':'d', 'ě':'e', 'ň': 'n', 'ř':'r', 'š':'s', 'ť':'t', 'ů':'u', 'ž':'z', 'Č':'C', 'Ď':'D', 'Ě':'E', 'Ň': 'N', 'Ř':'R', 'Š':'S', 'Ť':'T', 'Ů':'U', 'Ž':'Z', // polish 'ą':'a', 'ć':'c', 'ę':'e', 'ł':'l', 'ń':'n', 'ś':'s', 'ź':'z', 'ż':'z', 'Ą':'A', 'Ć':'C', 'Ę':'E', 'Ł':'L', 'Ń':'N', 'Ś':'S', 'Ź':'Z', 'Ż':'Z', // latvian 'ā':'a', 'ē':'e', 'ģ':'g', 'ī':'i', 'ķ':'k', 'ļ':'l', 'ņ':'n', 'ū':'u', 'Ā':'A', 'Ē':'E', 'Ģ':'G', 'Ī':'I', 'Ķ':'K', 'Ļ':'L', 'Ņ':'N', 'Ū':'U', // lithuanian 'ė':'e', 'į':'i', 'ų':'u', 'Ė': 'E', 'Į': 'I', 'Ų':'U', // romanian 'ț':'t', 'Ț':'T', 'ţ':'t', 'Ţ':'T', 'ș':'s', 'Ș':'S', 'ă':'a', 'Ă':'A', // vietnamese 'Ạ': 'A', 'Ả': 'A', 'Ầ': 'A', 'Ấ': 'A', 'Ậ': 'A', 'Ẩ': 'A', 'Ẫ': 'A', 'Ằ': 'A', 'Ắ': 'A', 'Ặ': 'A', 'Ẳ': 'A', 'Ẵ': 'A', 'Ẹ': 'E', 'Ẻ': 'E', 'Ẽ': 'E', 'Ề': 'E', 'Ế': 'E', 'Ệ': 'E', 'Ể': 'E', 'Ễ': 'E', 'Ị': 'I', 'Ỉ': 'I', 'Ĩ': 'I', 'Ọ': 'O', 'Ỏ': 'O', 'Ồ': 'O', 'Ố': 'O', 'Ộ': 'O', 'Ổ': 'O', 'Ỗ': 'O', 'Ơ': 'O', 'Ờ': 'O', 'Ớ': 'O', 'Ợ': 'O', 'Ở': 'O', 'Ỡ': 'O', 'Ụ': 'U', 'Ủ': 'U', 'Ũ': 'U', 'Ư': 'U', 'Ừ': 'U', 'Ứ': 'U', 'Ự': 'U', 'Ử': 'U', 'Ữ': 'U', 'Ỳ': 'Y', 'Ỵ': 'Y', 'Ỷ': 'Y', 'Ỹ': 'Y', 'Đ': 'D', 'ạ': 'a', 'ả': 'a', 'ầ': 'a', 'ấ': 'a', 'ậ': 'a', 'ẩ': 'a', 'ẫ': 'a', 'ằ': 'a', 'ắ': 'a', 'ặ': 'a', 'ẳ': 'a', 'ẵ': 'a', 'ẹ': 'e', 'ẻ': 'e', 'ẽ': 'e', 'ề': 'e', 'ế': 'e', 'ệ': 'e', 'ể': 'e', 'ễ': 'e', 'ị': 'i', 'ỉ': 'i', 'ĩ': 'i', 'ọ': 'o', 'ỏ': 'o', 'ồ': 'o', 'ố': 'o', 'ộ': 'o', 'ổ': 'o', 'ỗ': 'o', 'ơ': 'o', 'ờ': 'o', 'ớ': 'o', 'ợ': 'o', 'ở': 'o', 'ỡ': 'o', 'ụ': 'u', 'ủ': 'u', 'ũ': 'u', 'ư': 'u', 'ừ': 'u', 'ứ': 'u', 'ự': 'u', 'ử': 'u', 'ữ': 'u', 'ỳ': 'y', 'ỵ': 'y', 'ỷ': 'y', 'ỹ': 'y', 'đ': 'd', // currency '€': 'euro', '₢': 'cruzeiro', '₣': 'french franc', '£': 'pound', '₤': 'lira', '₥': 'mill', '₦': 'naira', '₧': 'peseta', '₨': 'rupee', '₩': 'won', '₪': 'new shequel', '₫': 'dong', '₭': 'kip', '₮': 'tugrik', '₯': 'drachma', '₰': 'penny', '₱': 'peso', '₲': 'guarani', '₳': 'austral', '₴': 'hryvnia', '₵': 'cedi', '¢': 'cent', '¥': 'yen', '元': 'yuan', '円': 'yen', '﷼': 'rial', '₠': 'ecu', '¤': 'currency', '฿': 'baht', "$": 'dollar', '₹': 'indian rupee', // symbols '©':'(c)', 'œ': 'oe', 'Œ': 'OE', '∑': 'sum', '®': '(r)', '†': '+', '“': '"', '”': '"', ''': "'", ''': "'", '∂': 'd', 'ƒ': 'f', '™': 'tm', '℠': 'sm', '…': '...', '˚': 'o', 'º': 'o', 'ª': 'a', '•': '*', '∆': 'delta', '∞': 'infinity', '♥': 'love', '&': 'and', '|': 'or', '<': 'less', '>': 'greater', }; slug.defaults.modes = { rfc3986: { replacement: '-', symbols: true, remove: null, lower: true, charmap: slug.defaults.charmap, multicharmap: slug.defaults.multicharmap, }, pretty: { replacement: '-', symbols: true, remove: /[.]/g, lower: false, charmap: slug.defaults.charmap, multicharmap: slug.defaults.multicharmap, }, }; // Be compatible with different module systems if (typeof define !== 'undefined' && define.amd) { // AMD // dont load symbols table in the browser for (var key in slug.defaults.modes) { if (!slug.defaults.modes.hasOwnProperty(key)) continue; slug.defaults.modes[key].symbols = false; } define([], function () {return slug}); } else if (typeof module !== 'undefined' && module.exports) { // CommonJS symbols(); // preload symbols table module.exports = slug; } else { // Script tag // dont load symbols table in the browser for (var key in slug.defaults.modes) { if (!slug.defaults.modes.hasOwnProperty(key)) continue; slug.defaults.modes[key].symbols = false; } root.slug = slug; } }(this)); var content = { 'topicVideo': { 'id': '197505065', 'categorySort': 18, 'categoryName': 'Hayatımızda Kimya', 'contentSort': 2, 'contentName': 'Yüzey Aktif Maddeler', 'fileName': 'KonuAnlatimi.mp4' } } function getContent(content, categoryId) { console.log(content.topicVideo); return { // _id: Random.id(), // other properties contentSlug: slug(content.topicVideo.contentName, undefined) }; } console.log(getContent(content, 1));

You can use.您可以使用。

function slug(string, opts) {
    console.log('log 1: -------');
    console.log('log 2: ' + string);
    console.log('log 3: ' + typeof string);
    string = String(string);
    ....
 }

暂无
暂无

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

相关问题 TypeError:无法读取未定义的属性“toString” - 为什么? - TypeError: Cannot read property 'toString' of undefined - why? 为什么得到“无法读取该对象的未定义属性...”? - Why do I get "Cannot read property…of undefined with this object? 为什么会出现“无法读取未定义的属性” props”? - Why do I get 'Cannot read property 'props' of undefined'? 我找不到原因“错误:无法读取未定义的属性 'toString'” - I can not find the reason “ERROR: Cannot read property ‘toString’ of undefined” 我有类型错误:无法读取未定义的属性“toString” - I have the TypeError: Cannot read property 'toString' of undefined 为什么在此简单的Meteor应用程序中出现“未捕获的TypeError:无法读取未定义的属性&#39;helpers&#39;”? - Why do I get, “Uncaught TypeError: Cannot read property 'helpers' of undefined” in this simple Meteor app? 为什么我会收到“未捕获的类型错误:无法读取 undefined(...) 的属性‘长度’”? - Why do I get "Uncaught TypeError: Cannot read property 'length' of undefined(…)"? 为什么在定义数据时会出现“无法读取未定义的属性”错误? - Why do I get a "cannot read property of undefined" error when the data is defined? 为什么我在使用长度方法时得到“TypeError:无法读取未定义的属性'长度'” - Why do I get "TypeError: Cannot read property 'length' of undefined" when using length method 为什么在 pug 模板中进行迭代时会出现“无法读取未定义的属性‘长度’”错误? - Why do I get a "Cannot read property 'length' of undefined" error when iterating in a pug template?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM