个人常用JS方法总结

374 阅读1分钟

前言

在项目开发过程中,经常涉及对字符串或者数组的操作。本文对项目中经常用的js方法做下总结,方便再次遇到时能够快速查阅。

Array常用方法

1. indexOf

indexOf() 方法返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。

const beasts = ["ant", "bison", "camel", "duck", "bison"];
console.log(beasts.indexOf("bison"));  // 1

可以指定起始位置:arr.indexOf(searchElement[, fromIndex])

console.log(beasts.indexOf("bison", 2));  // 4

2. filter

filter()  方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。通俗的理解方式就是先找到匹配元素,然后将其过滤丢弃掉。

const beasts = ["ant", "bison", "camel", "duck", "bison"];
const beasts_filter = beasts.filter((item) => item.indexOf("bison"));
console.log(beasts_filter);  // ["ant","camel","duck"]

3. slice

获取数组指定索引区间元素

const url_array = ["http://www","baidu","com"]
const url_array_slice = url_array.slice(1, 2);
console.log(url_array_slice);  // ["baidu"]

4. join

join()  方法将一个数组的所有元素连接成一个字符串并返回这个字符串.

const url_array = ["http://www", "baidu", "com"];
const url = url_array.join(".");
console.log(url);  // "http://www.baidu.com"

String常用方法

1. split

把字符串分割为字符串数组

const url = "http://www.baidu.com";
const url_array = url.split(".");
console.log(url_array);  // ["http://www","baidu","com"]

2. substr

字符串截取

const res = "helloworld";
const res_sub = res.substr(5, 9);
console.log(res_sub);  // "world"

3. parseInt

字符串转数字 parseInt("10")

参考文档

工具

在线调试js工具:CodePen