找出第一个不重复的值
var str = 'xdfhgbjhgvgcdxszdchgkjk';
function test(str){
var temp = {};
for(var i = 0; i < str.length; i++){
var item = str[i];
if(temp.hasOwnProperty(item)){
temp[item]++;
} else {
temp[item] = 1;
}
}
for(var key in temp){
var item = temp[key];
if(item === 1){
return key;
}
}
}
test(str);
闭包
function Test(a, b, c){
var d = 0;
this.a = a;
this.b = b;
this.c = c;
function e(){
d++;
console.log(d);
}
this.f = e;
}
var test1 = new Test();
test1.f(); // 1
test1.f(); // 2
var test2 = new Test();
test2.f(); // 1
数据类型
function test(){
console.log(typeof(arguments)); // 类数组
}
test(); // object
// 函数字面量,忽略函数名
var test = function a(){
console.log(test.name);
return 'a';
}
console.log(typeof(a));
// undefined -> typeof放一个没有声明的变量一定返回undefined
优化下面的程序
function test(day){
switch(day){
case 1:
console.log('Mon');
break;
case 2:
console.log('Tue');
break;
case 3:
console.log('Wed');
break;
case 4:
console.log('Thu');
break;
case 5:
console.log('Fri');
break;
case 6:
console.log('Sat');
break;
case 7:
console.log('Sun');
break;
default:
console.log('I don\'t know');
}
}
test(2)
test(2);
// 优化
function test(day){
var weekday = var weekday =[
'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'
];
weekday[day - 1] !== undefined ? console.log(weekday[day - 1])
: console.log('I don\'t know');
}
变形:将上面优化后的结果改为不准用day-1,直接用使用day,应该如何修改
test(2);
// 在数组的第一位前添加逗号,
function test(day){
var weekday = [,'Mon', 'Tue'];
weekday[day] !== undefined ? console.log(weekday[day])
: console.log('I don\'t know');
}