函数数组Javascript中的图像

问题描述 投票:-1回答:2

我正在开发基于星球大战回合制的点击游戏。播放的目的是从6个字符的数组中随机挑选4个可用字符中的1个。

我有几个问题:1这个图像链接要做什么是我能够瞄准它吗?

2如何将Characters();转换为可用的数组

function Character(name, health, attackPoints, counterAttackPoints, img) {
  this.name = name;
  this.health = health;
  this.attackPoints = attackPoints;
  this.counterAttackPoints = counterAttackPoints;
  this.img = img;

  console.log(name, attackPoints, counterAttackPoints);
}

var char1 = new Character('Han Solo', 100, 13, 10, '../assets/images/Han_Solo_depicted_in_promotional_image_for_Star_Wars_(1977).jpg');
var char2 = new Character('Chewbacca', 300, 10, 20, '../assets/images/Chewbacca-2-.jpg');
var char3 = new Character('Luke Skywalker', 140, 15, 12, '../assets/images/Luke_Skywalker.png');
var char4 = new Character('Darth Maul', 120, 12, 13, '../assets/images/Darth_Maul.png');
var char5 = new Character('Darth Vader', 175, 20, 6, '../assets/images/Han_Solo_depicted_in_promotional_image_for_Star_Wars_(1977).jpg');
var char6 = new Character('General Grievous', 120, 14, 10, '../assets/images/Han_Solo_depicted_in_promotional_image_for_Star_Wars_(1977).jpg');
javascript arrays html5 image
2个回答
0
投票

代替

var somethingNew = new Character(...)

您可以将新角色推送到数组中:

var characters = [];
characters.push(new Character('Han Solo', 100, 13, 10, '../assets/images/Han_Solo_depicted_in_promotional_image_for_Star_Wars_(1977).jpg'));
characters.push(new Character('Chewbacca', 300, 10, 20, '../assets/images/Chewbacca-2-.jpg'));
// etc

console.log(characters.length); // 2!

console.log(characters[0].name); // Han Solo

0
投票

如果我正确理解你的问题,你试图将一个对象变成某种类型的数组。

你可以使用Object.values()

const char1 = {
  name: 'Some Dude',
  health: 100,
  attackPoints: 13,
  counterAttackPoints: 10, 
  img: '../some/url/to/your/asset.jpg'
};

console.log(Object.values(char1)); 

// Output will be => ["Some Dude", 100, 13, 10, "../some/url/to/your/asset.jpg"]

如果你需要更深入地进入对象,就像在对象原型中循环一样,那么你需要选择一个for .. in循环

© www.soinside.com 2019 - 2024. All rights reserved.