我正在尝试为下面的我的类别对象创建一个模型:
let person = prompt ("Rock, Paper, Scissors");
// Computer makes a choice
function computerPlay () {
let compchoice = ['Rock', 'Paper', 'Scissors'];
return compchoice[Math.floor(Math.random() *
compchoice.length)];
}
//Player vs Computer
function playRound (playerSelection, computerSelection) {
if (playerSelection === 'Rock' || computerSelection ===
'Scissors') {
return 'You chose ' + playerSelection + ',' + ' You win!';
} else if (playerSelection === 'Paper' || computerSelection ===
'Rock')
{
return 'You chose ' + playerSelection + ',' + ' You win!';
} else if (playerSelection === 'Scissors' || computerSelection ===
'Paper')
{
return 'You chose ' + playerSelection + ',' + ' You win!';
} else if (computerSelection === 'Rock' || playerSelection ===
'Scissors')
{
return 'Computer chose ' + computerSelection + ',' + 'Computer
wins!';
} else if (computerSelection === 'Paper' || playerSelection ===
'Rock')
{
return 'Computer chose ' + computerSelection + ',' + 'Computer
wins!';
} else if (computerSelection === 'Scissors' || playerSelection ===
'Paper')
{
return 'Computer chose ' + computerSelection + ',' + 'Computer
wins!';
} else if (computerSelection === playerSelection) {
return 'Its a draw!';
}else {
return 'Please chose Rock, Paper, or Scissors';
}
}
const playerSelection = 'rock';
const computerSelection = computerPlay();
console.log(playRound(playerSelection, computerSelection));
我不确定如何为“类别”创建模型部分,因为数据项可以更改。例如,该API可以返回“汉堡”和“侧面”,而不是“三明治”和“比萨饼”。
这是我所拥有的:
{
"categories": [
{
"sandwiches": [
{
"name": "breadedChickenFlatbread",
"description": "A good sandwich",
"img": "./sandwich.jpg",
"price": "$8.99"
}
]
},
{
"pizzas": [
{
"name": "PizzaPie",
"price": "5milliondollars",
"img": "",
"description": ""
}
]
}
]
}
如何将对象中的类别名称映射到模型?还是应该更改响应对象
答案 0 :(得分:1)
因此可以输入以下类别:
interface Category {
[key:string]: Details[];
}
这是一个索引签名,基本上意味着类型类别具有一定数量的字符串键,这些字符串键将具有Details数组类型值。
您可以使用更严格的文字键入密钥:
type CategoryKey = 'pizzas'|'sandwiches'|'burgers'|'fries';
interface Category {
[key:CategoryKey]: Details[];
}
现在类别界面只能具有这些特定的键。