JavaScript "typeof" and "in"

本文介绍了一个简单的电梯控制逻辑实现方案,通过一个JavaScript函数控制电梯在四层楼间上下移动。文章详细解释了如何根据当前楼层和用户选择的目标楼层来决定电梯的移动方向,并确保输入的有效性和乘客的安全。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


Q:There is a house with 4 levels. In that house there is an elevator. You can program this elevator to go up or down, depending on what button the user touches inside the elevator.

levels can be only numbers: 0,1,2,3 buttons can be strings: '0','1','2','3' possible return values are numbers: -3,-2,-1,0,1,2,3

If the elevator is on the ground floor(0th level) and the user touches button '2' the elevator must go 2 levels up, so our function must return 2.

If the elevator is on the 3rd level and the user touches button '0' the elevator must go 3 levels down, so our function must return -3.

If the elevator is on the 2nd level, and the user touches button '2' the elevator must remain on the same level, so we return 0.

We cannot endanger the lives of our passengers, so if we get erronous inputs, our elevator must remain on the same level. So for example goto(2,'4') must return 0, because there is no button '4' in the elevator. goto(4,'0') must return 0, because there is no level 4. goto(3,undefined) must return 0. goto(undefined,'2') must return 0. goto([],'2') must return 0 because the type of the input level is array instead of a number. goto(3,{}) must return 0 because the type of the input button is object instead of a number.                                            


MyAnswer:

function goto(level,button){
   if(typeof(level)==="number"&&typeof(button)==="string"){
   		if(level>3||level<-3||parseInt(button)>3||parseInt(button)<-3){
   			return 0;	
   		}else{
   				return parseInt(button)-level;
   		}
   }else{
	  return 0;
	}
Master answer:

function goto(level,button){
  return level in [0,1,2,3] && button in [0,1,2,3] ? button - level : 0
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值