Object
let person = {
name:"Nicholas",
age:29
};
let people = new Object();
people.name = "Nicholas";
people.age = 29;
Array
创建数组
let colors = Array("red","yellow","green");
let arr = [1,2];
console.log(Array.from("Matt"));
const a1 = [1,2];
const a2 = Array.from(a1);
console.log(a2);
console.log(a1 === a2)
将字符串拆分为字符串数组 对现有数组浅复制
数组索引
let colors = ["red","yellow","green"];
colors.length = 2;
console.log(colors);
colors.length = 3;
console.log(colors);
通过修改length属性可以在数组末尾删除或添加元素
填充方法
let zeroes = [0,0,0,0,0];
zeroes.fill(5);
console.log(zeroes);
zeroes.fill(0);
zeroes.fill(6,3);
console.log(zeroes);
zeroes.fill(0);
zeroes.fill(7,1,3);
console.log(zeroes);
fill()方法一个参数全部填充参数 两个参数从第二个参数开始的位置填充第一个参数 三个参数从第二个参数开始到第三个参数区间填充第一个参数
栈方法
let colors = ["red","yellow","green"];
colors.push("black");
console.log(colors);
colors.pop();
console.log(colors);
数组通过push()和pop()方法把数组当作栈来使用
队列方法
同栈方法相似,通过shift()来取出数组的第一个值
排序
let a1 = [2,1,3,5];
console.log(a1.sort());
let a2 = [2,1,3,5];
a2.sort((a,b) => a < b ? 1 : a > b ? -1 : 0);
console.log(a2);
let a3 = [2,1,3,5];
console.log(a3.reverse());
reverse()和sort()方法 reverse()只是把数组反向排列 sort()默认按照升序重新排列数组元素 sort()可以接受一个比较函数,用于判断哪个值排在前面
操作方法
let colors = ["red","yellow","green"];
let colors2 = colors.concat("black");
console.log(colors);
console.log(colors2);
合并数组:concat()方法先创建当前数组的副本然后把参数加在副本的末尾
let colors = ["red","yellow","green"];
colors.splice(0,1);
console.log(colors);
删除:需要给splice()传两个参数,要删除的第一个元素位置和要删除的元素数量
let colors = ["red","yellow","green"];
colors.splice(1,0,"black");
console.log(colors);
插入:第一个参数开始位置,第二个参数要删除元素个数,后面的参数为插入的元素
let colors = ["red","yellow","green"];
colors.splice(1,1,"black");
console.log(colors);
替换:同插入
严格相等
let numbers = [1,2,3,4,3,6];
console.log(numbers.indexOf(3));
console.log(numbers.lastIndexOf(3));
console.log(numbers.indexOf(7));
console.log(numbers.includes(6));
indexOf()和lastIndexOf()都返回要查找的元素在数组的位置,无则返回-1 indexOf()从头开始找,而lastIndexOf()从末尾开始找 includes()返回布尔值 在比较的过程中会使用全等(===)比较
迭代方法
- every():每一项运行传入函数,每一项函数都是ture,则最终返回true
- filter():每一项运行传入函数,函数返回true的项会组成数组后返回
- forEach():每一项运行传入函数,没有返回值
- map():每一项运行传入函数,返回由每次函数调用返回结果构成的数组
- some():每一项运行传入函数,如果有一项函数返回true,则返回ture
let numbers = [1,2,3,4,5,4,3,2,1];
let everyResult = numbers.every((item,index,array) => item > 2 );
console.log(everyResult);
let someResult = numbers.some((item,index,array) => item > 2 );
console.log(someResult);
some()和every()相似,对于some来说只要有个返回true就返回true,而every则是所有返回true some():逻辑或 every():逻辑与
let filterResult = numbers.filter((item,index,array) => item > 2);
console.log(filterResult);
filter()方法把符合条件的元素组成数组返回
let mapResult = numbers.map((item,index,array) => item * 2);
console.log(mapResult);
map()方法则是把计算的结果组成数组返回 forEach()则是for循环来执行某些操作
|