ES6 中的字符串扩展
ES6 提供了多种新的字符串操作方法和特性。
1. 模板字符串(Template Strings)
使用反引号(`````)而非单引号或双引号来创建字符串,并允许插入变量:
javascript
const name = 'John';
const greeting = `Hello, ${name}!`;
console.log(greeting); // 输出 "Hello, John!"
2. 新增的字符串方法
startsWith
: 判断字符串是否以给定字符串开头endsWith
: 判断字符串是否以给定字符串结尾includes
: 判断字符串是否包含给定字符串repeat
: 重复字符串指定次数
javascript
const str = 'hello';
console.log(str.startsWith('he')); // true
console.log(str.endsWith('lo')); // true
console.log(str.includes('ell')); // true
console.log(str.repeat(2)); // 'hellohello'
ES6 中的函数扩展
1. 默认参数
在 ES6 中,函数参数可以有默认值。
javascript
function greet(name = 'John', age = 30) {
console.log(`Hello ${name}, you are ${age} years old.`);
}
greet(); // 输出 "Hello John, you are 30 years old."
greet('Jane', 25); // 输出 "Hello Jane, you are 25 years old."
2. Rest 参数
使用 ...
操作符接收多余的参数,这些参数被存储在一个数组中。
javascript
function sum(...numbers) {
return numbers.reduce((prev, curr) => prev + curr, 0);
}
console.log(sum(1, 2, 3, 4)); // 输出 10
3. 箭头函数(Arrow Functions)
箭头函数提供了一种更简洁的方式来写函数。
javascript
const square = x => x * x;
console.log(square(5)); // 输出 25
注意:箭头函数不绑定自己的 this
,arguments
,super
或 new.target
。这些函数表达式更适用于那些不需要自己的 this
值的函数。
4. 函数名属性
函数名属性 name
可以返回函数名。
javascript
function foo() {}
const bar = function() {};
console.log(foo.name); // 输出 "foo"
console.log(bar.name); // 输出 "bar" 在 ES6 中,匿名函数也能有 name 属性
以上只是 ES6 在字符串和函数方面的一些基础扩展。这些新特性使得 JavaScript 编程更加灵活和强大。希望这能帮助你更好地理解和使用 ES6。