// The global variable
var globalTitle = "Winter Is Coming";
// Only change code below this line
function urlSlug(title) {
return title
.split(" ")
.filter(x => x)
.join("-")
.toLowerCase();
}
// Only change code above this line
console.log(urlSlug(globalTitle))
// Result: winter-is-coming
我的疑问是关于此行:。filter(x => x),如何过滤数组中的空白?
[
'Winter',
'',
'',
'',
'Is',
'',
'',
'',
'',
'Coming'
]
然后将所有数组项传递到过滤器,过滤器将尝试将值转换为布尔值。将空白转换为布尔值将返回false。使用filter将保留元素,如果它返回true,那么您将得到以下结果:
[ 'Winter', 'Is', 'Coming' ]
完成此操作的另一种方法是使用.filter(Boolean)
。