2
回答
一道logicmonitor的前端js面试题
滴滴云服务器,限时包月0.9元,为开发者而生>>>   

前几天面试logicmonitor的一道js面试题。要求对以下房间信息进行排序:

var rooms = [
    "floor12room3",
    "floor1room12",
    "floor1room8", 
    "floor3room21", 
    "floor3room7", 
    "floor12room31",
    "floor1room24", 
    "floor2room13", 
    "floor3room14"
];

要求得到结果:

var rooms = [
    "floor1room8", 
    "floor1room12",
    "floor1room24", 
    "floor2room13", 
    "floor3room7",     
    "floor3room14",
    "floor3room21", 
    "floor12room3",
    "floor12room31"
];

当时脑壳晕晕的,只说了大概的思路。然而最终还是被刷了。各位路过的前端大佬能一试身手么?

<无标签>
举报
愤怒的晃晃
发帖于9个月前 2回/269阅
var rooms = [
    "floor12room3",
    "floor1room12",
    "floor1room8", 
    "floor3room21", 
    "floor3room7", 
    "floor12room31",
    "floor1room24", 
    "floor2room13", 
    "floor3room14"
];
let roomObjs = []
for(var i=0;i<rooms.length;i++){
	var temp = rooms[i].match(/floor(\d*)room(\d*)/)
	var objs = {
		"floor":temp[1],
		"room":temp[2],
		"all":rooms[i]
	}
	roomObjs.push(objs)
}
roomObjs.sort(function(a,b){
	if(a.floor - b.floor == 0){
		return a.room-b.room
	}
	return a.floor - b.floor
})
var newRooms = []
for(var i=0;i<roomObjs.length;i++){

	newRooms.push(roomObjs[i].all)
}
console.log(newRooms)

也可以直接在sort函数内直接提取并比较

引用来自“北极熊js”的评论

var rooms = [
    "floor12room3",
    "floor1room12",
    "floor1room8", 
    "floor3room21", 
    "floor3room7", 
    "floor12room31",
    "floor1room24", 
    "floor2room13", 
    "floor3room14"
];
let roomObjs = []
for(var i=0;i<rooms.length;i++){
	var temp = rooms[i].match(/floor(\d*)room(\d*)/)
	var objs = {
		"floor":temp[1],
		"room":temp[2],
		"all":rooms[i]
	}
	roomObjs.push(objs)
}
roomObjs.sort(function(a,b){
	if(a.floor - b.floor == 0){
		return a.room-b.room
	}
	return a.floor - b.floor
})
var newRooms = []
for(var i=0;i<roomObjs.length;i++){

	newRooms.push(roomObjs[i].all)
}
console.log(newRooms)

也可以直接在sort函数内直接提取并比较

不错不错,很好的实现方式哈,学习了!

顶部