property 'toString' of undefined"/>
为什么我得到 Cannot read property 'toString' of undefined
我用这个包。我在 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();
....
}
这里是输出:
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)
即使字符串参数的类型是字符串,
string.toString()
也会抛出 TypeError。它说字符串未定义。
我不是经验丰富的 js 开发人员。为什么会这样?
编辑: 我从这个函数调用它
function getContent(content, categoryId) {
console.log(content.topicVideo);
return {
// _id: Random.id(),
// other properties
contentSlug: slug(content.topicVideo.contentName, {
lower: true
})
};
}
新日志:
{ id: '197505065',
categorySort: 18,
categoryName: 'Hayatımızda Kimya',
contentSort: 2,
contentName: 'Yüzey Aktif Maddeler',
fileName: 'KonuAnlatimi.mp4' }
编辑:
我在 slug 函数的末尾添加了一个日志。
console.log(result);
return result;
};
打印结果然后抛出错误。
log 1: -------
log 2: Yüzey Aktif Maddeler
log 3: string
log 4: Yüzey Aktif Maddeler
yuzey-aktif-maddeler
编辑:我认为这一行给出了一个提示:
/Users/------/seeder/node_modules/mongodb/lib/utils.js:99
process.nextTick(function() { throw err; });
我认为它记录了正确的字符串,但是在没有记录日志的情况下未定义的字符串失败了。这可能吗?我发现 content.topicVideo.contentName 之一实际上是未定义的。但是在没有记录的情况下抛出了错误。这甚至可能吗?
回答如下:为了确保 .toString() 不会抛出错误,您可以:
string = "" + string; // amends the value to an string, even if its undefined or null etc
代替:
string = string.toString();
然而,您也可以检查字符串的值是否未定义或为空。 另见这里.
更多推荐
为什么我得到 Cannot read property 'toString' of undefined
发布评论