codewars练习(javascript)-2021/1/21

本文分享了四个JavaScript Codewars挑战,涉及幂运算、图像比例裁剪、基本函数修复及布尔值转字符串。通过解决这些8kyu级别问题,提升编程技能并理解16:9分辨率转换技巧。

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

codewars-js练习

2021/1/21

github 地址

my github地址,上面有做的习题记录,不断更新…

【1】<8kyu>【N-th Power】

You are given an array with positive numbers and a non-negative number N. You should find the N-th power of the element in the array with the index N. If N is outside of the array, then return -1. Don’t forget that the first element has the index 0.

example

array = [1, 2, 3, 4] and N = 2, then the result is 3^2 == 9;
array = [1, 2, 3] and N = 3, but N is outside of the array, so the result is -1.

solution:

<script type="text/javascript">
 		function index(array, n){
			var length = array.length;
			if(n>=length){
				return -1;
			}else{
				for(var i=0;i<length;i++){
					if(i == n){
						return Math.pow(array[i],n);
					}
				}
			}
		}
 		
		// 验证
		console.log(index([1, 2, 3, 4],2));//9
		console.log(index([1, 2],3));//-1
	</script>
【2】<8kyu>【Aspect Ratio Cropping - Part 1】

Write a function that accepts arbitrary X and Y resolutions and converts them into resolutions with a 16:9 aspect ratio that maintain equal height. Round your answers up to the nearest integer.

example

aspectRatio(640, 480)//[854,480]
aspectRatio(960,720)//[1280,720]

solution:

<script type="text/javascript">
 		function aspectRatio(x,y){
 			var width = Math.ceil(y*16/9);
 			var result = [width,y];
 			// console.log(result);
 			return result;
		}
 		
		// 验证
		console.log(aspectRatio(640, 480));//[854,480]
		console.log(aspectRatio(960,720));//[1280,720]
	</script>
【3】<8kyu>【Grasshopper - Basic Function Fixer】

I created this function to add five to any number that was passed in to it and return the new value. It doesn’t throw any errors but it returns the wrong number.

solution:

<script type="text/javascript">
 		function addFive(num) {
			var total = num + 5;
			return total
		}
 		
		// 验证
		console.log(addFive(5));//10
	</script>
【4】<8kyu>【Convert a Boolean to a String】

Implement a function which convert the given boolean value into its string representation.

example

booleanToString(true)//'true'

solution:

<script type="text/javascript">
 		function booleanToString(b){
			if(typeof b == 'boolean'){
				// console.log(typeof String(b));
				return String(b);
			}
		}
 		
		// 验证
		console.log(booleanToString(true));//'true'
	</script>

以上为自己思路供大家参考,可能有更优的思路。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值