function solve(commands){
let array = commands.shift();
commands.pop();
for(let command of commands){
let tokens = command.split(" ");
let currentCommand = tokens[0];
switch(currentCommand){
case "swap":
let index1 = array[tokens[1]];
let index2 = array[tokens[2]];
array[tokens[1]] = index2;
array[tokens[2]] = index1;
break;
case "multiply":
let index1 = array[tokens[1]];
let index2 = array[tokens[2]];
array[tokens[1]] = index1 * index2;
break;
case "decrease":
array.map((x)=>{
return x - 1;
});
break;
}
}
console.log(array);
}解决(['23 -2 321 87 - 42 90 -123','swap 1 3','swap 36 ','swap 10 ',将1乘以2,2乘以1,"减少","结束")
您忘记分割数组,并且您不能两次声明相同的变量。
function solve(commands) {
let array = commands.shift()
array = array.split(" ");
commands.pop();
for (let command of commands) {
let tokens = command.split(" ");
let currentCommand = tokens[0];
let index1, index2
switch (currentCommand) {
case "swap":
index1 = array[tokens[1]];
index2 = array[tokens[2]];
array[tokens[1]] = index2;
array[tokens[2]] = index1;
break;
case "multiply":
index1 = array[tokens[1]];
index2 = array[tokens[2]];
array[tokens[1]] = index1 * index2;
break;
case "decrease":
array.map((x) => {
return x - 1;
});
break;
}
}
console.log(array);
}
solve([
"23 -2 321 87 42 90 -123",
"swap 1 3",
"swap 3 6",
"swap 1 0",
"multiply 1 2",
"multiply 2 1",
"decrease",
"end",
]);