JavaScript常用的API——数组、字符串等

696 阅读8分钟

JavaScript常用的API

最近在做项目的时候经常用到一些数组、字符串的api,有些用起来还不是很得心应手,就想起来之前在 web前端开发 公众号看到的一篇api汇总,觉得很有用!在这里截取了一些我认为比较常用的api方便以后查阅~

a. Array

1. new Set()

数组去重

const arr = [3,4,4,5,4,6,5,7];
console.log(new Set(arr)); // {3,4,5,6,7}
const a = Array.from(new Set(arr)) // [3, 4, 5, 6, 7]
//或者
const a = [...new Set(arr)]//推荐

【...】的作用:遍历当前使用的对象能够访问到的时所用属性,并将该属性放入当前对象中,在开发中常用这种方式。

2. sort()

对数组元素进行排序(改变原数组)

const arr = [1,2,3,4,5,6];console.log(arr.sort((a,b)=>a-b)) 
// [1,2,3,4,5,6] 大小正序
cosole.log(arr.sort((a,b)=>b-a))
// [6,5,4,3,2,1] 大小倒序
//不可以进行运算的则比较编码大小  'b' > 'a' => true

3. reverse()

反转数组中的元素(改变原数组)。

const arr = [3,4,4,5,4,6,5,7];
conosle.log(arr.reverse());  
// [7, 6, 5, 5, 4, 4, 4, 3]

5. shift()

把数组的第一个元素从其中删除,并返回第一个元素的值(改变原数组)

const arr = [0,1,2];
const a = arr.shift(); //0
console.log(arr); // [1, 2]

6. unshift()

向数组的起始处添加一个或多个元素,并返回新的长度(改变原数组)

const arr = [3,4,4,5,4,6,5,7];
const a = arr.unshift(8);
console.log(a); // 9 (a为返回的数组的新长度)
console.log(arr); // [8, 3, 4, 4, 5, 4, 6, 5, 7]

7. push()

在数组的末端添加一个或多个元素,并返回添加新元素后的数组长度(改变原数组)

const arr = [3,4,4,5,4,6,5,7];
const a = arr.push(8,9);
console.log(a); // 10(a为返回的数组的新长度)
console.log(arr); // [3, 4, 4, 5, 4, 6, 5, 7, 8, 9]

8. toString()

可把值转换成字符串。

const arr = [3,4,4,5,4,6,5,7];
console.log(arr.toString()); // 3,4,4,5,4,6,5,7

9. join()

以参数作为分隔符,将所有参数组成一个字符串返回(默认逗号分隔)。

const arr = [3,4,4,5,4,6,5,7];
console.log(arr.join('-')); // 3-4-4-5-4-6-5-7

10. slice(start, end)

用于提取原来数组的一部分,会返回一个提取的新数组(深度拷贝),原数组不变(字符串适用,不包括 end)。

//数组
const arr = [3,4,4,5,4,6,5,7];
const a = arr.slice(2, 5); // [4, 5, 4]

//字符串
const x = 'abcdefgh';
const y = x.slice(3, 6); // def

11. splice()

用于删除原数组的一部分,并且可以在删除的位置添加新的数组成员,返回值是被删除的数组元素。(改变原数组)

splice(t, v, s)t: 被删除元素的起始位置;v:被删除元素个数;s:s 以及后面的元素为被插入的新元素。

const arr = [3,4,4,5,4,6,5,7];
const a = arr.splice(3, 2, 12); // [5, 4]
console.log(arr); // [3, 4, 4, 12, 6, 5, 7]

12. map()

依次遍历数组成员,根据遍历结果返回一个新数组。(不会改变原始数组)。

const arr = [3,4,4,5,4,6,5,7];
const a = arr.map(item => item*2;) 
// [6, 8, 8, 10, 8, 12, 10, 14]

13. forEach()

跟 map 方法类似,遍历数组,区别是无返回值。

const arr = [3,4,4,5,4,6,5,7];
arr.forEach(function(item,index,arr){console.log(value)}))  
//3  4  4  5  4  6  5  7

14. for in()

跟 map 方法类似,遍历对象或者数组。

但值得注意的是 for in 循环返回的值都是数据结构的键值名。遍历对象返回的对象的 key 值,遍历数组返回的数组的下标 (key)。

// 对象
const obj = {a: 123, b: 12, c: 2 };
for (let a in obj) {    
      console.log(a);
      }// a   b   c   
//数组
const arr = [3,4,4,5];
for(let a in arr) {
      console.log(a);
}// 0   1   2   3
for (var v of arr) {
     console.log(a);  
}// 3   4   4   5

15. filter()

一个过滤方法,参数是一个函数,所有的数组成员依次执行该函数,返回结果为 true 的成员组成一个新数组返回。(不会改变原始数组)

const arr = [3,4,4,5,4,6,5,7];
const a = arr.filter(item => item % 3 > 1);
console.log(a); // [5, 5]

16. some()& every()

这两个方法类似于 “断言”(assert),用来判断数组成员是否符合某种条件。

const arr = [3,4,4,5,4,6,5,7];

console.log( arr.some( function( item, index, array ){        console.log( 
    'item=' + item + 
    ',index='+ index +
    ', array='+ array );    
                                                              return item > 3;                                        }));
//   item=3,index=0,array=3,4,4,5,4,6,5,7
//   item=4,index=1,array=3,4,4,5,4,6,5,7
//   true

console.log( arr.every( function( item, index, array ){       console.log( 
    'item=' + item + 
    ',index='+index+
    ',array='+array );     
                                                     
      return item > 3;
    }));
//  item=3,index=0,array=3,4,4,5,4,6,5,7
//  false

some

some 方法是只要有一个数组成员的返回值为 true,则返回 true,否则 false;

every

every 方法是需要每一个返回值为 true,才能返回 true,否则为 false;

17. reduce()

依次处理数组的每个成员,最终累计成一个值。

格式:

reduce(() => (pre, cur, curIndex, arr), initialValue)

pre: 必填,累计变量;cur:必填,当前变量;curIndex: 可选,当前位置;arr: 可选,原数组;initialValue: 传递给函数的初始值。

18. indexOf()

返回给定元素在数组中的第一次出现的位置,如果没有则返回 - 1 (同样适用于字符串)。

//数组
const arr = [3,4,4,5,4,6,5,7];
console.log(arr.indexOf(4)) // 1
console.log(arr.indexOf('4'))  // -1

//字符串
const string = 'asdfghj';
console.log(string.indexOf('a')) // 0
lastIndexOf()

返回给定元素在数组中最后一次出现的位置,没有返回 - 1 (同样适用于字符串)。

const arr = [3,4,4,5,4,6,5,7];
console.log(arr.lastIndexOf(4)) 
// 4(从左到右数最后出现的位置,字符串同理)

19. flatten()

简写为 flat(),接收一个数组,无论这个数组里嵌套了多少个数组,flatten 最后都会把其变成一个一维数组 (扁平化)

const arr = [[1,2,3],[4,5,[6,7]]];
const a = arr.flatten(3);
console.log(a); // [1, 2, 3, 4, 5, 6, 7]

20. Array.isArray()

用来判断是不是数据是不是一个数组,返回值为 true 或 false。

const arr = [3,4,4,5,4,6,5,7];
console.log(Array.isArray(arr)) // true

21. find()

返回符合传入测试(函数)条件的数组元素

const arr = [3,4,4,5,4,6,5,7];
const a = arr.find(item => item > 3);
console.log(a); //4(find() 方法返回通过测试(函数内判断)的数组的第一个元素的值。)

const b = arr.find(item => item == 0);
console.log(b); //undefined(如果没有符合条件的元素返回 undefined)

b. String

1. match()

用于在字符串内检索指定的值或找到一个或多个正则表达式的匹配,返回的是值而不是值的位置。

const str = 'hello guys';console.log(str.match('guys'))  // ["guys"]

// 使用正则匹配字符串
const strs = '1.hello guys, 2.are you ok?';
console.log(strs.match(/\d+/g)) // ["1", "2"]

2. replace()

替换匹配的字符串。

const str = 'hello guys';
console.log(str.replace('guys', 'man'))  // hello man

抽出字符串中的某一项指定字符。

const str = 'AA_BB_CC.bin';
console.log(str.replace(/[^\_]/g),'')  // __(两个下划线)

3. search()

用于检索与字符串匹配的子串,返回的是地址,与 indexOf() 的区别是 search 是强制正则的,而 indexOf 只是按字符串匹配的。

const str = 'hello guys';
console.log(str.search('guys'))  // 6
console.log(str.indexOf('guys'))  // 6

// 区别
const string = 'abcdefg.1234';
console.log(string.search(/\./)) // 7(转译之后可以匹配到 . 的位置)
console.log(string.indexOf(/\./)) // -1 (相当于匹配/\./,找不到则返回-1,只能匹配字符串)

4. split()

将字符串切割成数组。

const str = 'hello guys';
console.log(str.split('')) // ["h", "e", "l", "l", "o", " ", "g", "u", "y", "s"] 
console.log(str.split('', 3)) //  ["h", "e", "l"]

5. toLocaleLowerCase()& toLowerCase()

将字符串转换成小写。

const str = 'hello guys';
console.log(str.toLocaleLowerCase())  // hello guys
console.log(str.toLowerCase())  //  hello guys

6. toLocaleUpperCase()& toUpperCase()

将字符串转换成大写。

const str = 'hello guys';
console.log(str.toLocaleUpperCase())  // HELLO GUYS
console.log(str.toUpperCase())  // HELLO GUYS

7. substr()

用于从起始索引号提取字符串中指定数目的字符。

const str = 'hello guys';
console.log(str.substr(2))  // llo guys
console.log(str.substr(2, 7))  // llo guy

8. substring()

用于提取字符串中两个指定索引号之间的字符。(与 slice() 和 substr() 方法不同的是,substring() 不接受负的参数。)

const str = 'hello guys';
console.log(str.substring(2))   // llo guys
console.log(str.substring(2, 7))  //  llo g

9. .trim()

去掉字符串两端的空格。

const str = '    hello guys    ';
console.log(str.trim()) // hello guys(不会改变原数组)

JSON

a. JSON.parse()

用于把字符串转化为对象。

const str = '{"name": "phoebe", "age": 20}';
const obj = JSON.parse(str)  // {name: "phoebe", age: 20}(object类型)

b. JSON.stringify()

用于把对象转化为字符串。

const obj = {"name": "Tins", "age": 22};
const str = JSON.stringify(obj)  // {"name":"Tins","age":22}(string类型)

typeOf()

typeof 可用来检测数据类型:需要注意的是 typeof 无法区分 null、Array 和 通常意义上的 object。

typeof 123 //number
typeof '123' //string
typeof true // boolean
typeof false //boolean
typeof undefined // undefined
typeof Math.abs // function
typeof function () {} // function

// 当遇上`null`、`Array`和通常意义上的`object`,都会返回 object
typeof null // object
typeof [] // object(所以判断数组时可以使用Array.isArray(arr))
typeof {} // object

// 当数据使用了new关键字和包装对象以后,数据都会变成Object类型,不加new关键字时会被当作普通的函数处理。
typeof new Number(123); //'object'
typeof Number(123); // 'number'
typeof new Boolean(true); //'object'
typeof Boolean(true); // 'boolean'
typeof new String(123); // 'object'typeof String(123); // 'string'

instanceOf()

instanceOf()运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链。

function Car(make, model, year) {  
    this.make = make;  
    this.model = model;  
    this.year = year;
}
const auto = new Car('Honda', 'Accord', 1998);

console.log(auto instanceof Car); // trueconsole.log(auto instanceof Object); // true