王培顺的博客&WangPeishun’s Blog

定义一个hello函数,参数传递名字时,返回hello,名字,参数为空时,返回hello,world。

hello "john" => "Hello, John!" 
hello "aliCE" => "Hello, Alice!" 
hello => "Hello, World!" # name not given 
hello ' ' => "Hello, World!" # name is an empty String

我的(我承认,是第二次做这个题目啦,自我感觉逻辑思维是硬伤!!!)

第一次:

function hello(name) { 
if (name != null){
if(name == ""){ return "Hello, World!"; }
else{ var array = name.toLowerCase().split(" "); 
for (i=0;i<array.length;i++) { 
array[i] = array[i][0].toUpperCase() + array[i].substring(1, array[i].length); } 
var string = array.join(" "); 
return "Hello, "+ string +"!"; } 
} 
else { return"Hello, World!"; } 
}

第二次:

function hello(name) { 
if(name){ 
var say = name.substr(0,1).toUpperCase()+name.substring(1).toLowerCase(); return "Hello, "+say+"!"; }
else{ return 'Hello, World!'; } 
}

人家的:

function hello(name){ 
if (name){ return "Hello, " + name.substring(0,1).toUpperCase() + name.substring(1).toLowerCase() + '!'; } else { return "Hello, World!"; } 
}

function hello(name) { 
if (name === undefined || name === '') { return 'Hello, World!'; } 
else { return 'Hello, ' + name.substring(0,1).toUpperCase() + name.substring(1).toLowerCase() + '!'; } 
} 

function hello(name) {
if (!(name)) { return 'Hello, World!'; } 
else { name = name.replace(name.charAt(0), name.charAt(0).toUpperCase()); name = name.replace(name.charAt(name.length - 1), name.charAt(name.length - 1).toLowerCase()); } 
return 'Hello, ' + name +'!'; 
} 

function hello(name = "World") { 
if (!name) name = "World" return "Hello, " + name.charAt(0).toUpperCase() + name.slice(1).toLowerCase() + "!"; 
}


标签: none

添加新评论