对象的扩展
- ES6允许直接写入变量和函数,作为对象的属性和方法。这样的书写更加简洁。
- ES6 允许字面量定义对象时,用方法二(表达式)作为对象的属性名,即把表达式放在方括号内。
let foo = "aaa";
let obj = { foo };
console.log(obj);
//ES6允许在对象之中,直接写变量。这时,属性名为变量名, 属性值为变量的值。
function f(x, y) {
return { x, y };
}
console.log(f(1, 2)); // Object {x: 1, y: 2}
var birth = '2000/01/01';
var Person = {
name: '张三',
//等同于birth: birth
birth,
// 等同于hello: function ()...
hello() { console.log('我的名字是', this.name); }
};
var birth = '2000/01/01';
var Person = {
name: '张三',
//等同于birth: birth
birth,
// 等同于hello: function ()...
hello() { console.log('我的名字是', this.name); }
};
//这种写法用于函数的返回值,将会非常方便。
function getPoint(){
var x=1;
var y=34;
return {x,y}
}
getPoint() //{x:1,y:34}
//ES6 允许字面量定义对象时,用方法二(表达式)作为对象的属性名,即把表达式放在方括号内。
let propKey = 'foo';
let obj1 = {
[propKey]: true,
['a' + 'bc']: 123
};
console.log(obj1);
}
函数的扩展
- es6允许为函数的参数设置默认值,即直接写在参数定义的后面
//es6允许为函数的参数设置默认值,即直接写在参数定义的后面
/* function log(x,y='Word'){
console.log(x, y);
}
log('hello')
log('hello','China')
log('hello','') */
ES6 引入rest参数
- (形式为“…变量名”),用于获取函数的多余参数
function sum(...result){
let sum=0;
for (let index = 0; index < result.length; index++) {
sum += result[index];
}
// console.log(sum);
}
sum(1,34,55);
扩展运算符
- 扩展运算符(spread)是三个点(…)。它好比rest参数的逆运算,将一个数组转为用逗号分隔的参数序列。
console.log(...[1, 2, 3]) //1 2 3
function push(array, ...items) {
array.push(...items);
console.log(array);
}
let arrlist=[];
push(arrlist,1,2,4,5)