题解 | #坐标移动#
坐标移动
https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
let commendStr = readline()
/** 给定原坐标,移动方向及移动距离,返回移动后的坐标 */
const move = ({x, y}, direction, distance) => {
if (direction === 'A') {
x -= distance
} else if (direction === 'W') {
y += distance
} else if (direction === 'S') {
y -= distance
} else if (direction === 'D') {
x += distance
}
return {
x,
y
}
}
/** 处理坐标字符串,移除不合法的坐标 */
const commends = (commendStr.split(';')).filter((commend) => {
return ['A', 'W', 'S', 'D'].includes(commend.charAt(0)) && !isNaN(commend.substring(1))
})
/** 初始坐标 */
let coord = {
x: 0,
y: 0
}
/** 遍历所有坐标,得到最终结果 */
commends.forEach(commend => {
coord = move(coord, commend.charAt(0), +commend.substring(1))
})
console.log(`${coord.x},${coord.y}`)

查看22道真题和解析