codewars练习(javascript)-2021/2/17

这篇博客分享了两道 Codewars 上的 JavaScript 练习题,分别是计算数组元素乘积的 `grow` 函数和实现单词首字母互换的 `spoonerize` 函数。通过示例代码详细解释了解题思路,供学习参考。

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

codewars-js练习

2021/2/17

github 地址

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

【1】<8kyu>【Beginner - Reduce but Grow】

Given a non-empty array of integers, return the result of multiplying the values together in order.

example

[1, 2, 3, 4] => 1 * 2 * 3 * 4 = 24

solution

	<script type="text/javascript">
    function grow(x){
      // console.log(x);
      var result=1;
      for(var i=0;i<x.length;i++){
        result *=x[i];
      }
      return result;
    }
 		
		// 验证
		console.log(grow([1,2,3,4]));// 24
	</script>
【2】<7kyu>【Spoonerize Me】

In its most basic form a spoonerism is a two word phrase in which only the first letters of each word are swapped:

“not picking” --> “pot nicking”

Your task is to create a function that takes a string of two words, separated by a space: words and returns a spoonerism of those words in a string, as in the above example.

首字母互换

example

"not picking" --> "pot nicking"

solution

	<script type="text/javascript">
    function spoonerize(words) {
      // console.log(words)
      var arr = words.split(' ');
      // console.log(arr)
      var arr1 =arr[0].split('')
      var arr2 = arr[1].split('')
      // console.log(arr1)
      // console.log(arr2)

      var temp1 = arr2[0]
      var temp2 = arr1[0]
      arr1.shift()
      arr2.shift()
      // console.log(arr2)
      // console.log('arr1',arr1)
      var result = temp1 + arr1.join('') +' '+ temp2 + arr2.join('')
      // console.log('result',result)
      return result

    }
 		
		// 验证
		console.log(spoonerize("nit picking"));//"pit nicking"
    console.log(spoonerize("jelly beans"));// "belly jeans"
	</script>

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值