我尝试循环的数组在下面的对象中称为commands
。我给它了一系列命令,我在下面的函数中定义了这些命令。我的for循环位于名为commandsArray()
的底部函数中。我尝试在程序中调用commandsArray()
来执行数组循环,但它不起作用。
我不确定我做错了什么。我肯定想在这里使用for循环,并尝试尽可能地工作。我是Javascript的新手。
var myRover = {
position: [[0],[0]],
direction: 'N',
roverDirections: ['N', 'E', 'S', 'W'],
marsGrid: [[0], [0]],
obstacles: [],
commands: ['f','f', 'f', 'r', 'f', 'f', 'l', 'f', 'f', 'f', 'b', 'b']
};
// MOVE FORWARD & BACKWARD COMMANDS
function move(command) {
if (command === 'f') { //FORWARD
switch(myRover.direction) {
case 'N':
myRover.position[0]++;
break;
case 'E':
myRover.position[1]++;
break;
case 'S':
myRover.position[0]--;
break;
case 'W':
myRover.position[1]--;
break;
}
}
else if (command === 'b') { //BACKWARD
switch(myRover.direction) {
case 'N':
myRover.position[0]--;
break;
case 'E':
myRover.position[1]--;
break;
case 'S':
myRover.position[0]++;
break;
case 'W':
myRover.position[1]++;
break;
}
}
return myRover.position;
}
// TURN COMMANDS
function turn(command){
if (command === 'l') { //TURNING LEFT
switch (myRover.direction) {
case 'N':
myRover.direction = 'W';
break;
case 'E':
myRover.direction = 'N';
break;
case 'S':
myRover.direction = 'E';
break;
case 'W':
myRover.direction = 'S';
break;
}
}
if (command === "r") { //TURNING RIGHT
switch (myRover.direction) {
case 'N':
myRover.direction = 'E';
break;
case 'E':
myRover.direction = 'S';
break;
case 'S':
myRover.direction = 'W';
break;
case 'W':
myRover.direction = 'N';
break;
}
}
return myRover.direction;
}
// Executing on a Series of Commands From the Commands Array
function commandsArray() {
var commandsLength = myRover.commands.length;
for (var i = 0; i <= commandsLength; i++) {
if (commandsLength[i] === 'f') {
move('f');
}
else if (commandsLength[i] === 'b') {
move('b');
}
if (commandsLength[i] === 'r') {
turn('r');
}
else if (commandsLength[i] === 'l') {
turn('l');
}
return myRover.position;
}
答案 0 :(得分:0)
从这段代码:
function commandsArray() {
var commandsLength = myRover.commands.length;
for (var i = 0; i <= commandsLength; i++) {
if (commandsLength[i] === 'f') {
move('f');
}
else if (commandsLength[i] === 'b') {
move('b');
}
if (commandsLength[i] === 'r') {
turn('r');
}
else if (commandsLength[i] === 'l') {
turn('l');
}
return myRover.position;
}
}
看起来return myRover.position
位于for
循环中。 myRover.commands
包含数组(不是commandsLength
)。试试这个:
function commandsArray() {
var commandsLength = myRover.commands.length;
for (var i = 0; i <= commandsLength; i++) {
if (myRover.commands[i] === 'f') {
move('f');
}
else if (myRover.commands[i] === 'b') {
move('b');
}
if (myRover.commands[i] === 'r') {
turn('r');
}
else if (myRover.commands[i] === 'l') {
turn('l');
}
}
return myRover.position;
}
或者更好:
function commandsArray() {
const turns = ['l', 'r'];
myRover.commands.forEach(command => {
if (turns.includes(command)) {
turn(command);
} else {
move(command);
}
});
return myRover.position;
}