1、对象的增删改查
var obj = {
name: 'jack',
age: 12,
weight: 45,
hight: 160,
say: function () {
console.log('i from china');
},
work: function () {
//不伦不类
// obj.hight++
// 对象里面,this 表示对象本身
this.hight++
console.log(obj.hight);//161
console.log('i will go to park');
},
eat: function () {
// obj.weight++
this.weight++
console.log(obj.weight);//46
console.log('i eating dinner');
}
}
// 删除对象的属性和方法
delete obj.say
delete obj.name
obj.address = 'jx'
obj.eat()//46
obj.work()//161
obj.work()//162
console.log(obj);
2、带参数的对象方法
function del() {
var num = 3
var arr = [1, 2, 3, 4, 5]
for (var i = 0; i < arr.length; i++) {
if (arr[i] === num) {
arr.splice(i, 1)
}
}
return arr
}
console.log(del());//(4) [1, 2, 4, 5]
结果一样
function del(num) {
// var num = 3
var arr = [1, 2, 3, 4, 5]
for (var i = 0; i < arr.length; i++) {
if (arr[i] === num) {
arr.splice(i, 1)
}
}
return arr
}
console.log(del(3));//(4) [1, 2, 4, 5]
var school = {
stu: [],
total: 6,
join: function (name) {
this.stu.push(name)
console.log(this.stu);
// if (this.stu.length === this.total) {
// console.log('到齐');
// } else {
// console.log('未到齐');
// }
this.stu.length === this.total ? console.log('到齐') : console.log('未到齐');
},
leave: function (name) {
// for (var i = 0; i < this.stu.length; i++) {
// if (this.stu[i] === name) {
// this.stu.splice(i, 1)
// }
// }
// 效果一样
var idx = this.stu.indexOf(name)
if (idx !== -1) {
this.stu.splice(idx, 1)
}
console.log(this.stu);
this.stu.length === this.total ? console.log('到齐') : console.log('未到齐');
console.log(name + `早退了`);
},
bye: function () {
this.stu = []
console.log('已下课');
console.log(this.stu);
}
}
school.join('12')
school.join('13')
school.join('14')
school.join('zhangsan')
school.join('lisi')
school.join('wangwu') //(6) ["12", "13", "14", "zhangsan", "lisi", "wangwu"]
school.leave('13') //(5) ["12", "14", "zhangsan", "lisi", "wangwu"]
school.bye()//[]