把数组中的名字首字母大写,其他的小写。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
//['adam', 'LISA', 'barT']
//['Adam', 'Lisa', 'Bart']
function normalizre(arr) {
var m = []; //定义一个空数组,用于存放新生成的名字集合。
var other = ''; //定义一个空字符串,用于存放新生成的名字。
for(var i = 0; i < arr.length; i++){ //遍历不符合要求的名字数组['adam', 'LISA', 'barT']。以adam为例。
var a = arr[i]; //将数组的第一个元素赋值给a。
//console.log(a); //i为0时输出adam。
//console.log(typeof a); //string
for(var j = 0; j < a.length; j++){ //遍历元素的每个值
if(j == 0){
var one = a[j].toUpperCase(); //将第一值变为大写。A
} else {
var other =other + a[j].toLowerCase(); //其他的值变为小写,并连接起来。dam
}
}
other = one + other; //将完整的名字连接起来。
//console.log(other); //Adam
m.push(other); //将新生成的名字放到定义的数组中。
var other = ''; //初始化一下other和one,如果不初始化,字符串拼接将导致名字出错。
var one = '';
}
console.log(m); //打印新生成的数组到控制台。一般是返回即:return m;
}
normalizre(['adam', 'LISA', 'barT']); //这是火狐浏览器里显示的结果。Array(3) [ "Adam", "Lisa", "Bart" ]
</script>
</body>
</html>