[英]I'm not understanding what's going on in this javascript object
我正在进行一些代码学校的javascript练习,而这部分让我感到困惑。 在函数dontPanic中,我不明白该语句末尾发生的情况
location.weaponBulbs[location["ranger"+i].station-1][0].
基本上是说station-1
。 我不确定为什么要从桩号对象中减去1。 我也看不懂站1之后的[0]。 [0]指的是哪个对象或数组?
我的猜测是第1站之后的[0]。 是分配给电台的号码,但我确实需要澄清一下。 我不想在不理解这一点的情况下继续学习本课程。 我在需要帮助理解的这一行上方添加了评论。
var superBlinders = [ ["Firestorm", 4000], ["Solar Death Ray", 6000], ["Supernova", 12000] ];
var lighthouseRock = {
gateClosed: true,
weaponBulbs: superBlinders,
capacity: 30,
secretPassageTo: "Underwater Outpost",
numRangers: 3,
ranger1: {name: "Nick Walsh", skillz: "magnification burn", station: 2},
ranger2: {name: "Drew Barontini", skillz: "uppercut launch", station: 3},
ranger3: {name: "Christine Wong", skillz: "bomb defusing", station: 1}
};
function dontPanic (location){
var list = "";
for(var i = 1; i<=location.numRangers; i++){
//this is what I don't understand
list = list + location["ranger" + i].name + ", man the " +
location.weaponBulbs[location["ranger"+i].station-1][0] +
"!\n";
}
alert("Avast, me hearties!\n" +
"There be Pirates nearby! Stations!\n" + list);
}
dontPanic(lighthouseRock);
因为数组的索引为0,而location["ranger"+i].station
的索引为1。 location.weaponBulbs
location.weaponBulbs[1]
实际上是数组中的第二个元素,而location.weaponBulbs[10]
同样访问第11个元素。
通过从整数location['ranger'+i].station
减去1,它将正确访问相关的数组值。
location.weaponBulbs
似乎是一个二维数组。
location["ranger"+i].station-1
产生一个整数,因此最终结果是
location.weaponBulbs[n][0]
,其中n
是location["ranger"+i].station-1
它正在从superBlinders
阵列中选择武器。
由于护林员编号从1到3开始,并且数组的索引从0到2开始,您需要从护林员编号中减去1才能直接将它们映射到武器。
"ranger"+i
产生一个字符串。 location.weaponBulbs
是一个数组-因此,位置可能看起来像这样...
var location = { "weaponBulbs":superBlinders, /* this is an array again */ ranger1: {name: "Nick Walsh", skillz: "magnification burn", station: 2}, ranger2: {name: "Drew Barontini", skillz: "uppercut launch", station: 3}, ranger3: {name: "Christine Wong", skillz: "bomb defusing", station: 1} ... }
location["ranger"+i].station
在此将成为一个int
最后,对于每个station
,它都会点亮随机的weaponBulb
强度...
谁我学会了如何用Javascript写石头!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.