我有这种游戏模式的XML:
<?xml version="1.0" ?>
<gameType>
<easy>
<numberOfLevels>2</numberOfLevels>
<levelGroup id="1">
<level id="1">[0]</level>
<level id="2">[1]</level>
<level id="3">[2,2]</level>
</levelGroup>
<levelGroup id="2">
<level id="1">[0]</level>
<level id="2">[1]</level>
<level id="3">[3,2]</level>
</levelGroup>
</easy>
<medium>
<numberOfLevels>1</numberOfLevels>
<levelGroup id="1">
<level id="1">[0,2]</level>
<level id="2">[1,4]</level>
<level id="3">[2,5,6]</level>
</levelGroup>
</medium>
我想要做的是获得适当游戏模式的所有等级。例如:
//we get the list of all games
var xmlDoc = $(xml);
//we get number of levels for the selected game mode, default gameMode = 'easy'
var games = xmlDoc.find(gameMode).find("numberOfLevels")[0].textContent;
//we select a game by choosing a random number
var selectedGameIndex = $.random(games);
//Here I want to filter out only the appropriate elements, eg, in the default
//game mode and with the selectedGameIndex set to '1', I want to return an
//array that contains only the values,
//eg. var resultArray = [[0],[1]....[2,11,12]]; What I got is this:
var elements = sandbox.baseLib.$(gameMode + " > levelGroup[id='"
+ selectedGameIndex + "']", xmlDoc).children();
var predefinedIndexSequence = elements.map(function() {
return sandbox.baseLib.$(this).text();
}).get();
gameLength = gameSequence.size();
编辑:这是正确的代码(至少我需要它)。错误是当我实际上不需要过滤器的结果时尝试过滤xmlDoc,我需要使用“elements”变量制作的数组。
答案 0 :(得分:1)
您可以使用.map()缩写代码的最后一个块(从var levelsArray
开始):
return elementsArray.map(function() {
return $(this).text();
});
...虽然我称之为$elements
而不是elementsArray
,因为它看起来实际上是一个jQuery对象,而不是一个真正的数组。如果我错了并且它不是jQuery对象,请改为:
return $.map(elementsArray,function(el,i) {
return el.textContent;
});
您也可以将var games = xmlDoc.find(gameMode).find("numberOfLevels")[0].textContent
替换为var games = xmlDoc.find(gameMode).find("numberOfLevels:eq(0)").text()
,虽然这不会更短,只是更像jQuery。