[英]JS - returning values from class after instantiated
我正在查看下面的代碼,並希望在調用以下代碼時以相反的順序返回團隊數組。 不幸的是,此代碼無法更改。
return Array.from(new TeamsCollection()).join(',')
我知道我可以將constructor
更改為以下內容:
constructor(){
return this.teams.reverse();
}
正如您在下面看到的,我無法編輯構造函數,所以一定還有其他我遺漏的東西。 在閱讀了無數堆棧溢出答案並搜索在線資源后,我無法弄清楚該怎么做。 有任何想法嗎? 請參閱下面的代碼
class TeamsCollection {
get teams() {
return [
'Liverpool',
'Chelsea',
'Barca'
]
}
// The constructor cannot be changed
constructor(){
return this
}
}
Array.from
方法將可迭代的 object 轉換為數組,練習希望您在TeamsCollection
上實現可迭代協議:
class TeamsCollection {
get teams() {
return ['Liverpool', 'Chelsea', 'Barca']
}
*[Symbol.iterator]() {
yield* this.teams.reverse(); // or write a decrement loop that yields the elements
}
}
你應該from
function 覆蓋。
class TeamsCollection {
get teams() {
return [
'Liverpool',
'Chelsea',
'Barca'
]
}
// The constructor cannot be changed! Do not edit!
constructor(){
return this
}
}
var oldFrom = Array.from;
Array.from = function(obj , mapFunc ) {
if(obj && Array.isArray(obj.teams)) {
if(mapFunc) {
return obj.teams.map(mapFunc);
}
return obj.teams
}
return oldFrom(obj , mapFunc)
}
console.log(Array.from(new TeamsCollection()).join(","))
console.log(Array.from([1,2,3]).join(","))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.