有没有一种方法可以将对象从对象推送到数组?(Vue)



我试图制作一个游戏来开始学习JavaScript,但遇到了这个问题,我找不到答案。基本上,我想把一个已经创建的对象,在这种情况下是"firstIPGenerator",推送到一个名为"IPGenerators"的数组中,该数组位于另一个称为"layer"的对象内部。出于某种原因,它说"PGenerators"数组是"Undefined">

//This will declare the player
var player = {
IPPoints: 0,
IPGenerators: [],
EXPPoints: 10,
EXPGenerators: [],
XPEPoints: 10,
XPEGenerators: [],
PEXPoints: 10,
PEXGenerators: []
}
//This will declare the first IPGenerator of the game
var firstIPGenerator = {
cost: 5,
mult: 1,
amount: 0,
bought: 0
}
//This will declare the first EXPGenerator of the game
var firstEXPGenerator = {
cost: 5,
mult: 1,
amount: 0,
bought: 0
}
//This will push the already created ''firstIPGenerator'' to the ''IPGenerators'' array
player.IPGenerators.push(firstIPGenerator)
//This will push the already created ''firstEXPGenerator'' to the ''EXPGenerators'' array
player.EXPGenerators.push(firstEXPGenerator)
console.log(player);

同时,"layer"将转到正在创建Vue 的index.js

var app = new Vue({
el: '#app', 
data: {
message: 'Hola Pibe',
player: player
},
methods: {

}
})

这是HTML代码

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/styles.css">

<title>Incrementalism</title>
</head>
<body>
<div id="app">
<div class="IPPoints-container">
{{ message }}
</div>
<div class="IPPointsGen-container">
<!--This will print the cost of every IPGenerator-->
<div class="generator IPPoints-generator" v-for="IPGenerators in player.IPGenerators">
{{ IPGenerators.cost }}
</div>
</div>
<!--From here it's not important-->
<div class="triGenPoints-container">
<div class="EXPPoints-container">
</div>
<div class="XPEPoints-container">
</div>
<div class="PEXPoints-container">
</div>
</div>
<div class="triGenerators-container">
<div class="triGenerator EXPPoints-generator" v-for= "EXPPoints in player.EXPPoints">
{{ EXPGenerators.cost }}
</div>
<div class="triGenerator EXPPoints-generator">
</div>
<div class="triGenerator EXPPoints-generator">

</div>
</div>
</div>
<script src="js/vue.js"></script>
<script src="js/player.js"></script>
<script src="js/index.js"></script>
</body>
</html>

我对这一切都很陌生,所以我要感谢所有能帮助的人

我敢肯定你的问题是你在引用玩家时没有使用"这个";。以下内容应该有效。

this.players.IPGenerators.push(firstIPGenerator);

数据方法中定义的项目必须使用";这个";。

最新更新