for…in
可以遍历数组和对象
var arr = ["html", "js", "jq"];
for (p in arr) {
console.log(p); // 0 1 2
console.log(arr[p]); // html js jq
}
var arr = {
"html": '结构',
"css": '样式',
"js": '功能'
};
for (p in arr) {
console.log(p); // html css js
console.log(arr[p]); // 结构 样式 功能
}
使用函数的好处
- 增加代码的复用性
- 统一修改和维护
- 增加代码的可读性,使代码具有语义化
函数的本质
是对象
// 添加属性和方法
function add(num1, num2) {
return num1 + num2;
}
add.sex = 'male';
add.setSex = function (sex) {
this.sex = sex;
}
console.log(add.sex);
console.log(add.setSex('female'));
console.log(add.sex);
console.log(add(1, 2));
// 作为数据值使用
var add = function () {
return 1;
};
console.log(add()); // 执行函数
console.log(add); // 打印函数
// 作为参数
setTimeout(function () {
console.log(1);
}, 1000);
setTimeout(fn, 1000); // 匿名函数等于命名函数不加()
function fn() {
console.log(1);
}
// 作为返回值
function fn() {
return function () {
console.log(1);
};
}
fn()(); // fn()得到的是返回值,在调用一次打印1
函数定义
// function声明
function add() {
// body...
}
add();
// var赋值表达式
var add = function (argument) {
// body...
};
add();
// 全局作用域
add()
function add() {
// body...
add()
}
add()
// 函数作用域
fn()X
function add() {
fn();
function fn() {
fn()
function fn3(argument) {
fn()
}
// body...
}
function fn2() {
fn();
// body...
}
}
fn()X
// if/else等代码块
if (true) {
var add = function (argument) {
// body...
}
} else {
var subtract = function (argument) {
// body...
}
}
add = undefined; // js没有代码块的作用域,在预加载时是undefined
subtract = undefined; // 只有执行到了相对区域才会赋值
add = function (argument) {
// body...
}
// 对象
var person = {
name: 'xm',
setSex: function (sex) {
this.sex = sex;
}
};
person.setName = function (name) {
this.name = name;
}
person.setSex();
函数的调用
var add = function () { // 匿名函数的执行不能以function打头,所以可以加一些东西
console.log(1);
}();
(function () { // 没有实际意义,只是避免function打头
console.log(1);
})();
// 递归调用
function factorial(num) {
if (num <= 1) return 1;
return num * factorial(num - 1);
// return 5 * 4! = 5 * 4 * 3! =... 5 * 4 * 1!
}
console.log(factorial(5));
console.log(factorial(4));
// 间接调用
var name = 'xm';
var person = {};
person.name = 'xh';
person.getName = function () {
return this.name;
};
console.log(person.getName());
console.log(person.getName.call(window)); // 将this指向为window
console.log(person.getName.apply(window)); // 只有一个参数call和apply无区别
function add(num1, num2) {
return num1 + num2;
}
var datas = [1, 2];
console.log(add.call(window, 1, 2)); // 传递参数只能一个个写
console.log(add.apply(window, datas)); // 传递参数要写数组
var arr = [1, 2, 3];
var max = Math.max.apply(null, arr); // 取最大值
console.log(max);
传参
// 数组
$.each([1, 2, 3], function (index, item) {
console.log(index);
console.log(item);
});
// 对象
function setPerson(obj) { // 多个参数时,使用对象来传参,可以避免错误
var person = {};
person.name = obj.name || 'xh';
person.sex = obj.sex || 'male';
person.age = obj.age || '18';
person.tel = obj.tel || '110';
person.addr = obj.addr || 'China';
}
setPerson({
name: 'xm',
age: '18',
addr: 'China',
sex: 'male'
});