Even number should be return Uppercase

时间:2017-12-18 06:47:04

标签: javascript node.js

Create a function on String that takes an integer n as parameter.
If n is an even number, it should return the string in uppercase.
If n is odd, it should return the string in lowercase.

Basically, I need to write a script to make the following possible.

'stringname'.functionName(5) should return 'stringname' 'stringname'.functionName(4) should return 'STRINGNAME'

var i=2;
module.exports = function(i) {
     return String(stringname)["to"+(i%2?"Low":"Upp")+"erCase"]();    
}

but unfortunately I'm not able to achieve my desired output.

3 个答案:

答案 0 :(得分:4)

String.prototype.upperIfEven = function(n){
   return (n % 2 == 0) ? this.toUpperCase() : this.toLowerCase();
}

var odd = "Hello".upperIfEven(5)

var even = "Hello".upperIfEven(6)

console.log("Odd -> ",odd)

console.log("Even -> ",even)

答案 1 :(得分:3)

function upperIfEven(input, n) {
    return (n % 2 == 0) ? input.toUpperCase() : input.toLowerCase();
}

console.log(upperIfEven('Hello World', 10));
console.log(upperIfEven('Hello World', 3));

答案 2 :(得分:0)

您可以使用带有方法名称的数组,根据偶数/奇数值更改个案。



function upperIfEven(input, n) {
    return input[['toUpperCase', 'toLowerCase'][n % 2]]();
}

console.log(upperIfEven('Hello World', 10));
console.log(upperIfEven('Hello World', 3));