JavaScript基础知识梳理

for…of & for…in

for…of

mdn上的解释:for…of语句在可迭代对象(包括 Array,Map,Set,String,TypedArray,arguments 对象等等)上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function* foo(){
yield 1;
yield 2;
}
for (let o of foo()) {
console.log(o);
}
// 1 2

let str = 'abcd';
for (let i of str) {
console.log(i);
}
// "a" "b" "c" "d"

for…in

mdn上的解释:for…in语句以任意顺序遍历一个对象的除Symbol以外的可枚举属性。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var obj = {a:1, b:2, c:3};
for (var prop in obj) {
console.log(prop);
}
// "a" "b" "c"

// 也可以遍历数组
let arr = [3,4,5];
for(let i in arr){
console.log(i, arr[i])
}
// "0" 3
// "1" 4
// "2" 5

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//for of  for in 
let arr = ['a','b','c'];
//迭代每一项的值,一般适用于数组 或者
//for of 是用来迭代那些实现了迭代器功能的对象
for(let item of arr){
console.log(item); // a b c
}
for(let item in arr){
console.log(item); // 0 1 2
}
let obj = {name:'jiafei',age:10}
//for in 是 迭代对的属性的
for(let item in obj){
console.log(item); // name age
}

Array.from & …

Array 对数组的操作

slice

slice() 方法返回一个新的数组对象,这一对象是一个由 begin 和 end 决定的原数组的浅拷贝(包括 begin,不包括end)。原始数组不会被改变。

1
2
3
4
5
6
7
8
9
10
var animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// Array ["bison", "camel", "duck", "elephant"]

split

split() 方法使用指定的分隔符字符串将一个String对象分割成字符串数组,以将字符串分隔为子字符串,以确定每个拆分的位置。

1
2
3
4
5
6
7
8
9
var str = 'The quick brown fox jumps over the lazy dog.';

var words = str.split(' ');
console.log(words[3]);
// expected output: "fox"

var chars = str.split('');
console.log(chars);
// expected output: "k"

pop 、unshift、shift

pop

includes

concat

concat() 方法用于合并两个或多个数组。此方法不会更改现有数组,而是返回一个新数组

1
2
3
4
5
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f', 'a];

console.log(array1.concat(array2));
// expected output: Array ["a", "b", "c", "d", "e", "f"]