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 3 6', 'swap 1 0', '乘以1 2', '乘以2 1', '減少', '結尾' ])
uj5u.com熱心網友回復:
您忘記拆分陣列,并且不能兩次宣告相同的變數。
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",
]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/330965.html
標籤:javascript 数组
