let apples = ['🍎', '🍏'];
let fruits = ['🥭', '🍌', '🍒'];
// Add all items from apples onto fruits at start
Array.prototype.unshift.apply(fruits, apples)
console.log( fruits );
//=> ["🍎", "🍏", "🥭", "🍌", "🍒"]
现在红苹果和绿苹果会在开头位置合并而不是末尾。
简写方法:
我们依然可以使用ES6扩展运算符(...
)缩短这段长代码,如下所示:
let apples = ['🍎', '🍏'];
let fruits = [...apples, '🥭', '🍌', '🍒']; // <-- here
console.log( fruits );
//=> ["🍎", "🍏", "🥭", "🍌", "🍒"]
[](
)3. 克隆数组
普通写法:
我们可以使用Array
中的slice()
方法轻松克隆数组,如下所示:
let fruits = ['🍉', '🍊', '🍇', '🍎'];
let cloneFruits = fruits.slice();
console.log( cloneFruits );
//=> ["🍉", "🍊", "🍇", "🍎"]
简写方法:
我们可以使用ES6扩展运算符(...
)像这样克隆一个数组:
let fruits = ['🍉', '🍊', '🍇', '🍎'];
let cloneFruits = [...fruits]; // <-- here
console.log( cloneFruits );
//=> ["🍉", "🍊", "🍇", "🍎"]
[](
)4. 解构赋值
普通写法:
在处理数组时,我们有时需要将数组“解包”成一堆变量,如下所示:
let apples = ['🍎', '🍏'];
let redApple = apples[0];
let greenApple = apples[1];
console.log( redApple ); //=> 🍎
console.log( greenApple ); //=> 🍏
简写方法:
我们可以通过解构赋值用一行代码实现相同的结果:
let apples = ['🍎', '🍏'];
let [redApple, greenApple] = apples; // <-- here
console.log( redApple ); //=> 🍎
console.log( greenApple ); //=> 🍏
[](
)5. 模板字面量
普通写法:
通常,当我们必须向字符串添加表达式时,我们会这样做:
// Display name in between two strings
let name = 'Palash';
console.log('Hello, ' + name + '!');
//=> Hello, Palash!
// Add & Subtract two numbers
let num1 = 20;
let num2 = 10;
console.log('Sum = ' + (num1 + num2) + ' and Subtract = ' + (num1 - num2));
//=> Sum = 30 and Subtract = 10
简写方法:
通过模板字面量,我们可以使用反引号(),这样我们就可以将表达式包装在
${…}`中,然后嵌入到字符串,如下所示:
// Display name in between two strings
let name = 'Palash';
console.log(`Hello, ${name}!`); // <-- No need to use + var + anymore
//=> Hello, Palash!
// Add two numbers
let num1 = 20;
let num2 = 10;
console.log(`Sum = ${num1 + num2} and Subtract = ${num1 - num2}`);
//=> Sum = 30 and Subtract = 10
[](
)6. For循环
普通写法:
我们可以使用for
循环像这样循环遍历一个数组:
let fruits = ['🍉', '🍊', '🍇', '🍎'];
// Loop through each fruit
for (let index = 0; index < fruits.length; index++) {
console.log( fruits[index] ); // <-- get the fruit at current index
}
//=> 🍉
//=> 🍊
//=> 🍇
//=> 🍎
简写方法:
我们可以使用for...of
语句实现相同的结果,而代码要少得多,如下所示:
let fruits = ['🍉', '🍊', '🍇', '🍎'];
// Using for...of statement
for (let fruit of fruits) {
console.log( fruit );
}
//=> 🍉
//=> 🍊
//=> 🍇
//=> 🍎
[](
)7. 箭头函数
普通写法:
要遍历数组,我们还可以使用Array
中的forEach()
方法。但是需要写很多代码,虽然比最常见的for
循环要少,但仍然比for...of
语句多一点:
let fruits = ['🍉', '🍊', '🍇', '🍎'];
// Using forEach method
fruits.forEach(function(fruit){
console.log( fruit );
});
//=> 🍉
//=> 🍊
//=> 🍇
//=> 🍎
简写方法:
但是使用箭头函数表达式,允许我们用一行编写完整的循环代码,如下所示:
let fruits = ['🍉', '🍊', '🍇', '🍎'];
fruits.forEach(fruit => console.log( fruit )); // <-- Magic ✨
//=> 🍉
//=> 🍊
//=> 🍇
//=> 🍎
大多数时候我使用的是带箭头函数的forEach
循环,这里我把for...of
语句和forEach
循环都展示出来,方便大家根据自己的喜好使用代码。
[](
)8. 在数组中查找对象
普通写法:
要通过其中一个属性从对象数组中查找对象的话,我们通常使用for
循环:
let inventory = [
{name: 'Bananas', quantity: 5},
{name: 'Apples', quantity: 10},
{name: 'Grapes', quantity: 2}
];