首页 > 其他分享 >js常用方法总结

js常用方法总结

时间:2022-11-16 22:23:48浏览次数:49  
标签:总结 返回 常用 item cars js var 数组 字符串

数组方法

  1 let fruits = ["Banana", "Orange", "Apple", "Mango"];
  2   //获取数组长度
  3   fruits.length; //4
  4   // toString() 把数组转换为数组值(逗号分隔)的字符串
  5   fruits.toString(); //Banana,Orange,Apple,Mango
  6   // join() 方法也可将所有数组元素结合为一个字符串。它的行为类似 toString(),但是您还可以规定分隔符
  7   fruits.join(" * "); //Banana * Orange * Apple * Mango
  8 
  9   // pop() 删除并返回数组的最后一个元素
 10   const f1 = fruits.pop(); // "Mango"
 11   // shift() 把数组的第一个元素从其中删除,并返回第一个元素的值
 12   const f2 = fruits.shift(); //"Banana"
 13   // push() 向数组的末尾添加一个或多个元素,并返回新的长度。
 14   fruits.push("Kiwi", "lemon"); //4
 15   //unshift() 方法可向数组的开头添加一个或更多元素,并返回新的长度。
 16   fruits.unshift("Lemon"); //5
 17 
 18   // splice() 从数组中添加/删除项目,然后返回被删除的项目
 19   //参数1  规定添加/删除项目的位置, 参数2 要删除的项目数量,设置为0则不会删除项目  其余参数定义要添加的新元素
 20   fruits.splice(2, 0, "Lemon", "Kiwi"); //['Lemon', 'Orange', 'Lemon', 'Kiwi', 'Apple', 'Kiwi', 'lemon']
 21 
 22   // concat() 方法通过合并(连接)现有数组来创建一个新数组
 23   let fruits1 = ["lemon"];
 24   let fruits2 = ["waterlemon"];
 25   let fruits3 = fruits.concat(fruits1, fruits2); //['Lemon', 'Orange', 'Lemon', 'Kiwi', 'Apple', 'Kiwi', 'lemon', 'lemon', 'waterlemon']
 26 
 27   // slice()  选取数组的一部分,并返回一个新数组,该方法会从开始参数选取元素,直到结束参数(不包括)为止
 28   let somFriuts = fruits.slice(1, 3); //['Orange', 'Lemon']
 29 
 30   // sort() 方法以字母顺序对数组进行排序
 31   fruits.sort(); //['Apple', 'Kiwi', 'Kiwi', 'Lemon', 'Lemon', 'Orange', 'lemon']
 32   // reverse() 方法反转数组中的元素
 33   fruits.reverse(); // ['lemon', 'Orange', 'Lemon', 'Lemon', 'Kiwi', 'Kiwi', 'Apple']
 34   // sort() 方法以数字顺序对数组进行排序
 35   var points = [40, 100, 1, 5, 25, 10];
 36   points.sort(function (a, b) {
 37     return a - b;
 38   }); //[1, 5, 10, 25, 40, 100]
 39   var cars = [
 40     { type: "Volvo", year: 2016 },
 41     { type: "Saab", year: 2001 },
 42     { type: "BMW", year: 2010 },
 43   ];
 44   cars.sort(function (a, b) {
 45     return a.year - b.year;
 46   }); // [{type: 'Saab', year: 2001},{type: 'BMW', year: 2010},{type: 'Volvo', year: 2016}]
 47 
 48   // forEach() 方法为每个数组元素调用一次函数(回调函数)
 49   cars.forEach(function (item, index, cars) {
 50     // console.log(item, index, cars);
 51   });
 52 
 53   // map() 元素为值类型,新数组改变,原数组不改变。元素为引用类型,原数组会被改变
 54   // 想要原数组不变,可以用下面这种方式解决
 55   const newcars1 = cars.map(function (item, index, cars) {
 56     return Object.assign({ cat: 1 }, item); // 实际上也是浅拷贝
 57   }); //[{cat: 1,type: 'Saab', year: 2001},{cat: 1,type: 'BMW', year: 2010},{cat: 1,type: 'Volvo', year: 2016}]
 58   // filter() 如果返回真,就要,返回假,就不要
 59   const newcars = cars.filter(function (item, index, cars) {
 60     return item.year > 2015;
 61   }); //[{type: 'Volvo', year: 2016}]
 62 
 63   // reduce() 方法在每个数组元素上运行函数,以生成单个值,在数组中从左到右工作
 64   // reduceRight() 同reduce(),在数组中从右到左工作
 65   // reduce total为初始值,起初调用时默认为第一个元素,下一次调用时它将变为返回值
 66   let arr = [1, 2, 3, 4, 5];
 67   const total = arr.reduce(function (total, value, index, arr) {
 68     return total + value;
 69   }); //15
 70   // reduce  如果给了它初始值,total的初始值就会变为给定的初始值0
 71   const total1 = arr.reduce(function (total, value, index, arr) {
 72     return total + value;
 73   }, 0); //15
 74   //使用reduce函数计算数组元素个数
 75   function arrayCount(array, item) {
 76     return array.reduce(function (total, cur) {
 77       total += item == cur ? 1 : 0;
 78       return total;
 79     }, 0);
 80   }
 81   console.log(arrayCount(arr, 1)); //1
 82   //使用reduce函数计算数组最大值
 83   function arrayMax(array) {
 84     return array.reduce(function (pre, cur) {
 85       return pre > cur ? pre : cur;
 86     });
 87   }
 88   console.log(arrayMax(arr)); //5
 89   //使用reduce函数处理对象
 90   let cart = [
 91     { name: "iphone", price: 12000 },
 92     { name: "mac", price: 18000 },
 93     { name: "ipad", price: 3200 },
 94   ];
 95   function maxPrice(goods) {
 96     return goods.reduce(function (pre, cur) {
 97       return pre.price > cur.price ? pre : cur;
 98     });
 99   }
100   console.log(maxPrice(cart)); //{name: "mac", price: 18000}
101   function totalPrice(goods) {
102     return goods.reduce(function (total, cur) {
103       return (total += cur["price"]);
104     }, 0);
105   }
106   console.log(totalPrice(cart)); //33200
107 
108   // every() 方法检查所有数组值是否通过测试
109   const res = cars.every(function (item, index, cars) {
110     return item.year > 2010;
111   });
112   // some() 方法检查某些数组值是否通过了测试
113   const res1 = cars.some(function (item, index, cars) {
114     return item.year > 2015;
115   });
116 
117   // indexOf() 搜索数组中的元素,并返回它所在的位置
118   let a = fruits.indexOf("Apple", 1); //6
119   // lastIndexOf() 与 indexOf() 类似,但是从数组结尾开始搜索
120   let c = fruits.lastIndexOf("Apple", 1); //6
121   // find() 和 findIndex()
122   const cc = cars.find(function (item) {
123     return item.name == "mac";
124   }); //   { name: "mac", price: 18000 }
125   const index = cars.findIndex(function (item) {
126     return item.name == "mac";
127   }); //1
128 
129   // includes() 判断一个数组是否包含一个指定的值。
130   let b = fruits.includes("Banana"); //false
131   // join() 返回以指定分割符分割的数组元素的字符串
132   const str = arr.join(",");
133   // flat()把数组里嵌套的数组变成一维数组(扁平化)
134   const arr1 = [
135     [2, 4],
136     [4, 7],
137   ];
138   const arr2 = arr1.flat();
139   // Array.isArray() 用来判断是不是数据是不是一个数组,返回值为true或false
140   Array.isArray(arr2); //true
141   // copyWithin() 从数组的指定位置拷贝元素到数组的另一个指定位置中
142   //参数1 拷贝的目标位置  参数2 拷贝开始位置  参数3 拷贝结束位置
143   arr.copyWithin(1, 3);
144   //数组去重
145   [...new Set(arr)];

字符串方法

 1 // length 属性返回字符串的长度
 2   str.length;
 3   // indexOf() 方法返回字符串中指定文本首次出现的索引(位置)
 4   str.indexOf(subStr, startIdx);
 5   // lastIndexOf() 方法返回指定文本在字符串中最后一次出现的索引
 6   str.lastIndexOf(subStr, startIdx);
 7   // search() 方法搜索特定值的字符串,并返回匹配的位置  search() 方法无法设置第二个开始位置参数 indexOf() 方法无法设置更强大的搜索值(正则表达式)
 8   str.search(/\d/g);
 9   // slice() 提取字符串的两个索引之间的部分并在新字符串中返回被提取的部分。该方法设置两个参数:起始索引(开始位置),终止索引(结束位置)
10   str.slice(7, 13);
11   // substring() 类似于 slice()。不同之处在于 substring() 无法接受负的索引
12   str.substring(7, 13);
13   // substr() 类似于 slice()。不同之处在于第二个参数规定被提取部分的长度
14   str.substr(7, 6);
15   // replace() 方法用另一个值替换在字符串中指定的值,返回新字符串,默认地,replace() 只替换首个匹配
16   var n = str.replace(/MICROSOFT/i, "W3School");
17   // replace() 方法 如需替换所有匹配,请使用正则表达式的 g 标志(用于全局搜索)
18   var n = str.replace(/Microsoft/g, "W3School");
19   // toUpperCase() 把字符串转换为大写
20   var text2 = text1.toUpperCase();
21   // toLowerCase() 把字符串转换为小写
22   var text2 = text1.toLowerCase();
23   // concat() 连接两个或多个字符串
24   var text3 = text1.concat(" ", text2);
25   // trim() 方法删除字符串两端的空白符
26   var str3 = str.trim();
27   // charAt() 方法返回字符串中指定下标(位置)的字符串
28   str.charAt(0);
29   // charCodeAt() 方法返回字符串中指定索引的字符 unicode 编码
30   str.charCodeAt(0);
31   // split() 将字符串转换为数组
32   txt.split(",");
33   // match() match() 方法根据正则表达式在字符串中搜索匹配项,并将匹配项作为 Array 对象返回,
34   // 如果正则表达式不包含 g 修饰符(执行全局搜索),match() 方法将只返回字符串中的第一个匹配项
35   str.match(/\d/g);
36   // includes()如果字符串包含指定值,includes() 方法返回 true
37   text.includes("world", start);
38   // startsWith()如果字符串以指定值开头,则 startsWith() 方法返回 true,否则返回 false
39   text.startsWith("Hello", start);
40   // endsWith()如果字符串以指定值结尾,则 endsWith() 方法返回 true,否则返回 false
41   text.endsWith("Gates", length);

 

时间日期方法

 1 // getDate() 从 Date 对象返回一个月中的某一天 (1 ~ 31)
 2   var d = new Date();
 3   var dd = d.getDate();
 4   // getDay()  从 Date 对象返回一周中的某一天 (0 ~ 6)
 5   var dd1 = d.getDay();
 6   // getFullYear()  从 Date 对象以四位数字返回年份
 7   var y = d.getFullYear();
 8   // getHours() 返回 Date 对象的小时 (0 ~ 23)
 9   var h = d.getHours();
10   // getMinutes() 返回 Date 对象的分钟 (0 ~ 59)
11   var m = d.getMinutes();
12   // getMonth()  从 Date 对象返回月份 (0 ~ 11)
13   var mm = d.getMonth();
14   // getSeconds()  返回 Date 对象的秒数 (0 ~ 59)
15   var s = d.getSeconds();
16   // getTime() //获取时间戳
17   var s = d.getTime(); //获取时间戳
18   // setDate()  设置 Date 对象中月的某一天 (1 ~ 31)
19   d.setDate(15);
20   // setFullYear()  设置 Date 对象中的年份(四位数字)
21   d.setFullYear(2020);
22   // setHours()   设置 Date 对象中的小时 (0 ~ 23)
23   d.setHours(15);
24   // setMinutes() 设置 Date 对象中的分钟 (0 ~ 59)
25   d.setMinutes(17);
26   // setMonth() 设置 Date 对象中月份 (0 ~ 11)
27   d.setMonth(4);
28 
29   var date = new Date();
30   // getMilliseconds()返回 Date 对象的毫秒(0 ~ 999)
31   const ms = d.getMilliseconds();
32   // Date.parse()返回1970年1月1日午夜到指定日期(字符串)的毫秒数
33   var ms1 = Date.parse("2022-07-25 14:25:25");

 

遍历方法

 1  var cars = [
 2     { type: "Volvo", year: 2016 },
 3     { type: "Saab", year: 2001 },
 4     { type: "BMW", year: 2010 },
 5   ];
 6   // 传统的for循环
 7   for (let i = 0; i < cars.length; i++) {
 8     console.log(cars[i]);
 9   }
10   // for of 方法
11   for (let item of cars) {
12     console.log(item);
13   }
14   // 迭代器方法
15   for (let index of cars.keys()) {
16     console.log(index);
17   }
18   for (let item of cars.values()) {
19     console.log(item);
20   }
21   for (let [index, item] of cars.entries()) {
22     console.log(index, item);
23   }
24   // for in 方法
25   for (let key in cars) {
26     console.log(key, cars[key]);
27   }

 

Object对象方法
 1   // Object常用方法
 2   const obj = { a: 1, b: 2 };
 3   // Object.keys()会返回一个给定对象的自身可枚举属性组成的数组
 4   Object.keys(obj); //['a','b'];
 5   // Object.values():返回一个给定对象自身的所有可枚举属性值的数组
 6   Object.values(obj); //[1,2];
 7   // Object.entries():返回一个给定对象自身可枚举属性的键值对数组
 8   Object.entries(obj); //[['a', 1],['b', 2]];
 9   // Object.fromEntries():把键值对列表转换为一个对象,是Object.entries()的逆操作
10   Object.fromEntries(Object.entries(obj));
11   // hasOwnProperty():返回一个布尔值,指示对象自身属性中是否具有指定的属性
12   Object.hasOwnProperty(); //-------------------------------------------------------
13   // Object.assign():用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象
14   let s = { a: 1, b: 3 };
15   let t = { b: 4, c: 5 };
16   let r = Object.assign(s, t); // r:{a: 1, b: 4, c: 5}  t:{b: 4, c: 5}
17   // Object.is() 判断两个变量是否相同
18   let s1 = { a: 1, b: 3 };
19   Object.is(s, s1);

 

 其它对象方法

 1   // Number 对象
 2   // toExponential() 返回字符串值,它包含已被四舍五入并使用指数计数法的数字。参数定义小数点后的字符数
 3   var x = 9.656;
 4   x.toExponential(2); //返回 9.66e+0
 5   // toFixed() 返回字符串值,它包含了指定位数小数的数字
 6   x.toFixed(2); //// 返回 9.66
 7   // toPrecision() 返回字符串值,它包含了指定长度的数字
 8   x.toPrecision(2); // 返回 9.7
 9 
10   //  Math对象
11   //返回介于 0(包含) ~ 1(不包含) 之间的一个随机数:
12   Math.random();
13   //round() 方法可把一个数字舍入为最接近的整数:
14   Math.round(2.5); //3
15   // floor(x) 对 x 进行下舍入
16   Math.floor(1.6); //1
17   // ceil(x) 对数进行上舍入
18   Math.ceil(1.4); //2
19   // abs(x) 返回数的绝对值
20   Math.abs(-1); //1
21   // max(x,y) 返回 x 和 y 中的最大值
22   Math.max(2, 5); //5
23   // min(x,y) 返回 x 和 y 中的最小值
24   Math.min(2, 5); //2
25   // pow(x,y) 返回 x 的 y 次幂
26   Math.pow(2, 2); //4
27   // sqrt(x) 返回数的平方根
28   Math.sqrt(4); //2
29 
30   // JSON 方法
31   // parse() 解析一个字符串(以 JSON 格式编写)并返回一个 JavaScript 对象
32   const obj = Json.parse(strObj);
33   // stringify() 将 JavaScript 对象转换为字符串
34   const str1 = Json.stringify(strObj);
35 
36   // RegExp对象
37   // exec() 检索字符串中指定的值。返回找到的值,并确定其位置。
38   var str = "Hello world! Hello";
39   var patt = /Hello/gi;
40   var result = patt.exec(str);
41   // test() 检索字符串中指定的值。返回 true 或 false
42   var result1 = patt.test(str); //true
43 
44   //全局方法
45   // decodeURI() 解码某个编码的 URI
46   let uri = decodeURI("http://localhost:3000/1.html");
47   // encodeURI() 把字符串编码为 URI
48   let uri1 = encodeURI("http://localhost:3000/1.html");
49   // escape():对字符串进行编码
50   const es = escape("?!=()#%&"); //%3F%21%3D%28%29%23%25%26
51   // unescape():对由 escape() 编码的字符串进行解码
52   unescape(es); //?!=()#%&
53   // eval():计算 JavaScript 字符串,并把它作为脚本代码来执行
54   eval(3 + 4); //7
55   // isNaN():检查某个值是否不是数字
56   isNaN("hello"); //true
57   // Number():把对象的值转换为数字
58   Number("99.00"); //99
59   Number(false); //0
60   // parseFloat():解析一个字符串并返回一个浮点数
61   parseFloat("99.00 n"); //99
62   // parseInt():解析一个字符串并返回一个整数
63   parseInt("10"); //10
64   parseInt("10", 8); //8
65   // String():把对象的值转换为字符串
66   String(10); //字符串10
67   //判断一个值是否是无穷大
68   isFinite(n);
69 
70   // Function对象
71   //将函数作为指定对象的方法来调用,传递给它的是指定的参数数组
72   var personFunc = {
73     fullName: function (city, country) {
74       return this.firstName + " " + this.lastName + "," + city + "," + country;
75     },
76   };
77   var person = {
78     firstName: "Bill",
79     lastName: "Gates",
80   };
81   personFunc.fullName.apply(person, ["Oslo", "Norway"]);
82   // 在数组上模拟 max 方法
83   Math.max.apply(null, [1, 2, 3]); // 也会返回 3
84   //将函数作为指定对象的方法来调用,传递给它的是指定的参数
85   var personFunc1 = {
86     fullName: function (city, country) {
87       return this.firstName + " " + this.lastName + "," + city + "," + country;
88     },
89   };
90   var person1 = {
91     firstName: "Bill",
92     lastName: "Gates",
93   };
94   personFunc1.fullName.call(person1, "Seattle", "USA");

 

标签:总结,返回,常用,item,cars,js,var,数组,字符串
From: https://www.cnblogs.com/caroline2016/p/16897761.html

相关文章

  • nodejs dayjs 时间戳转化时间格式
    Unix时间戳day.js可以轻松转换秒级和毫秒级时间戳:dayjs().unix();//秒dayjs().valueOf();//毫秒letss=dayjs.unix('1668580898').format('YYYY-MM-DDHH:mm:ss'......
  • oled显示屏(128*64bit)使用——stm32学习总结
    正点原子oled显示屏教程,驱动程序有些缺陷:1.正点采用的取模方式:从上到下,再从左到右,纵向8点上高位。虽然正点原子提供了取模软件,但是软件的图像取模,没有自带滤波以及色阶选......
  • P4054 [JSOI2009] 计数问题
    传送门二维树状数组板子题(大概?)只要再多开一维\(c\)来存储该点的权值就可以了。这里的树状数组\(a[i][j][c]\)表示以第\(i\)行,第\(j\)列为右下角,权值为\(c\)的点......
  • 常用软件
    硬件调试1、串口模拟工具ConfigureVirtualSerialPortDriver2、串口调试工具UartAssist3、图标下载网站https://www.iconfont.cn/4、制作ico图标http://favicon......
  • Win10 常用命令
    1、查询端口,杀死进程netstat-ano|findstr<端口号>taskkill-PID<进程号>-F2、查看系统信息msinfo323、系统配置msconfig4、本地用户和组lusrmgr.msc5、分区管理diskpa......
  • YouTube JSON字幕格式转srt格式并下载
    <?phpfunctionformatNum(int$time){if($time<10){return"0{$time}";}return$time;}functionchangeTimeType(int$num):string{......
  • 2022.11.16 模拟赛总结
    2022.11.16模拟赛总结\(T1\)看起来对于我不是很可做,就大概看了一下\(50\)的做法,然后光速跳到\(T2\),\(T2\)打了个表把规律看出来了,然后又套了个组合意义,大概\(15m......
  • 深入剖析nodejs中间件
    nodejs的出现为前端行业带来了无限的可能性,让很多原来只负责客户端开发的同学也慢慢开始接触和使用服务器端技术.虽然nodejs带来了很多的好处,但是它也存在自身的局限性.......
  • 深入nodejs的event-loop
    此处如无特殊指出的话,eventloop的语境都是指nodejs本文研究所用的nodejs环境是:操作系统window10+nodejs版本号为v12.16.2什么是eventloop?eventloop是指由libuv......
  • 工作总结:kafka踩过的坑
    餐饮系统每天中午和晚上用餐高峰期,系统的并发量不容小觑。公司规定各部门都要轮流值班,防止出现线上问题时能够及时处理。后厨显示系统属于订单的下游业务。用户点完菜......