Common methods of arrays and strings

1. Do not change the original array

join() joins each item of the array with a delimiter

Parameter: the specified delimiter (if this parameter is omitted, a comma is used as the delimiter)

Return value: spliced ​​string

Whether to change the original array: no change

let arr = [1,2,3,4,5]
let newArr = arr.join('-')
console.log(newArr); // 1-2-3-4-5

concat() concatenates elements from two or more arrays into a new array

Parameter: The parameter can be a specific value or an array object. can be any number of

Return value: return the new array after concatenation

Whether to change the original array: no change

<!-- 例子一 -->
let arr1 = [1,2,3];
let arr2 = [4,5,6];
let arr = arr1.concat(arr2);//arr = [1,2,3,4,5,6];

<!-- 例子二 -->
let arr1 = ['你'];
let arr2 = ary1.concat('好');
console.log(arr2);//["你", "好"]

split() specifies a delimiter in the string to split the string into an array

let str = hello-world;
let arr = str.split('-');
console.log(arr);// arr=['hello','world'];

slice() intercepts the specified item in the array

parameter:

array.slice(n, m), search from index n to m (not including m) (header but not tail)

array.slice(n) If the second parameter is omitted, it will search until the end

array.slice() or array.slice(0) outputs the content as it is, which can realize array cloning

array.slice(-n,-m) slice supports negative parameters, counting from the last item, -1 is the last item, -2 is the penultimate item

Note: When using negative numbers, ensure that the order of interception is from left to right, otherwise the interception result is an empty array and does not contain the end item

Return value: return a new array

let arr = [0,1,2,3,4,5,6,7,8,9]; 
let newArr = arr.slice(2,8);
console.log(newArr); //从索引2开始查找到索引为8的内容,结果为[2, 3, 4, 5, 6, 7, 8] 
let newArr2 = arr.slice(2)
console.log(newArr2); //从索引2开始查找,一直查找到末尾,结果为[2, 3, 4, 5, 6, 7, 8, 9]
let newArr3 = arr.slice()
console.log(newArr3) //克隆数组
let newArr4 = arr.slice(-2,-1)
console.log(newArr4);//从最后的索引开始找,找到倒数第二的索引项,结果为[8, 9]
//要保证截取的顺序从左到右,否则截取结果为空数组,并且不包含末尾项

indexOf() detects the index of the first occurrence of the current value in the array

Parameters: array.indexOf(item,start) item: The element to search for start: The position in the string to start searching (optional)

Return value: the index found for the first time, if not found, return -1

Whether to change the original array: no change

let arr = ['a','b','c','d','e','a','f'];   
console.log(arr.indexOf('c'));//2
console.log(arr.indexOf('a',3))//5
console.log(arr.indexOf('x'));//-1

lastIndexOf() detects the index of the last occurrence of the current value in the array

Parameters: array.lastIndexOf(item,start) item: the element to search for start: the position in the string to start searching

Return value: the index found for the first time, if not found, return -1

Whether to change the original array: no change

let arr = ['a','b','c','d','e','a','f'];   
console.log(arr.lastIndexOf('c'));//2
console.log(arr.lastIndexOf('f',1))//-1

find() finds the item that meets the criteria and returns the first item

let arr = [
  { id: 3, name: "ls", done: false },
  { id: 1, name: "zs", done: true },
  { id: 2, name: "ww", done: true }
];
 var res = arr.find(function(item) {
   return item.done;
});
console.log(res);

findIndex() finds the subscript of the eligible item and returns the first one

let arr = [
  { id: 3, name: "ls", done: false },
  { id: 1, name: "zs", done: true },
  { id: 2, name: "ww", done: true }
];
var res = arr.findIndex(function(item) {
  return item.done;
});
console.log(res);

includes() Determines whether an array contains a specified value

Parameters: specified content

Return value: Boolean, true or false

Whether to change the original array: no change

let arr = ['a','b','c','d']; 
console.log(arr.includes('c'));//true
console.log(arr.includes(2));//false

forEach() traverses the array

Parameters: function arr.forEach(function(item,index,currentArray){}) item: each item index: index currentArray: current array

Return value: None

Whether to change the original array: no change

forEach中不能使用continue和break,forEach中不能跳出,只能跳过(return跳过)
let arr = ['a','b','c','d']; 
arr.forEach(function(item,index,currentArray){
console.log(item,index,currentArray);
})

map() is used to transform arrays

Parameters: function arr.map(function(item,index,currentArray){}) item: each item index: index currentArray: current array

Return value: return a new array

Whether to change the original array: change

let arr = [1,32,54,6,5];
let newArr = arr.map(function(item,index,currentArray){
    return item*2;
})
console.log(newArr);   //[2,64,108,12,10]

filter() filter

Parameters: function arr.filter(function(item,index){}) item: each item index: index

Return value: elements that meet the conditions (filter out items with a Boolean type of true)

Whether to change the original array: no change

let arr = [1, 3, 5, 2, 4, 6];
let newArr = arr.filter(function(item, index) {
  return item % 2 === 0;
});
console.log(newArr);   //[2,4,6]

some() Determines whether there are eligible items in the array (as long as there is one, return true, otherwise return false)

let arr = [
  { name: "zs", age: 18, done: "ok" },
  { name: "ls", age: 20, done: true },
  { name: "ww", age: 22, done: true }
];
let res = arr.some(function(item) {
  return item.done;
});
console.log(res);   //true

every() Determines whether all items in the array meet the requirements (if all are met, return true, otherwise return false)

let arr = [
  { name: "zs", age: 18, done: "ok" },
  { name: "ls", age: 20, done: true },
  { name: "ww", age: 22, done: true }
];
let res = arr.every(function(item) {
  return item.done;
});
console.log(res);   //true

reduce()

// let newArr = arr.reduce(function(叠加后的数据,数组中的项){
//    叠加后的数据 + 数组中的项;
// }, 从几开始累加)
let arr = [10,20,30]
let newArr = arr.reduce((sum,item) => sum+item, 0)
console.log(newArr)   //60
    var arr2 = [[1,2,3],[4,5],[6,7]] ;
    var new2 = arr2.reduce(function(pre,next,index){
            return pre.concat(next);    //前数组拼接后数组 .concat()
    })
     console.log(new2);
    var arr3 = [
    {price:10,count:1},
    {price:15,count:2},
    {price:10,count:3}
    ];
    var new3 = arr3.reduce(function(pre,next,index){
            return pre+next.price*next.count;
    },0)    //在原数组第一项添加为0,不改变原数组,则可不操作第一项
    console.log(new3);

Second, change the original array

splice() adds, deletes, and modifies an array

Delete: arr.splice(n,m) starts from index n, deletes m content, returns the new deleted array, and changes the original array

(Note: if the second parameter is omitted, delete from n to the end)

Added: arr.splice(n,0,m) deletes 0 items from index n, inserts m or more content in front of index n, and returns an empty array

Replacement: arr.splice(n,m,x) starts from subscript n, deletes m, and replaces the deleted part with x

//删除
let arr = [0,1,2,3,4,5];
//console.log(arr.splice(3,2))//[0, 1, 2, 5]
console.log(arr.splice(3));//[0, 1, 2]
//增加
let arr2 = [0,1,2,3,4,5];
arr2.splice(2,0,'a','b')
console.log(arr2);// [0, 1, "a", "b", 2, 3, 4, 5]
//修改
let arr3 = [0,1,2,3,4,5];
arr3.splice(1,2,'x','y')
console.log(arr3);// [0, 'x', 'y', 3, 4, 5]

push() adds new content to the end of the array (add returns the length of the array, delete returns the deleted item)

Parameters: The item to add. Pass multiple separated by commas, any data type is fine

Return value: the length of the array after adding

Whether to change the original array: change

let arr = [1,2,3];
arr.push(100); //返回一个新的长度,arr.length=4
console.log(arr)//结果为 [1,2,3,100]

unshift() adds new content to the first position of the array

Parameters: Items to be added, separated by ','

Return value: the length of the new array

Whether to change the original array: change

let arr = [1,2,3];
arr.unshift(100); //返回一个新的长度,arr.length=4
console.log(arr)//结果为 [100,1,2,3]

pop() removes the last item of the array

Parameters: none

Return value: the item that was removed

Whether to change the original array: change

let arr = [1,2,3];
arr.pop(); //返回被删除的项, 3
console.log(arr)//结果为 [1,2]

shift() removes the first item of the array

Parameters: none

Return value: the item that was removed

Whether to change the original array: change

let arr = [1,2,3];
arr.shift(); //返回被删除的项, 1
console.log(arr)//结果为 [2, 3]

reverse() flips the array

Parameters: none

Return value: the new array after reverse order

Whether to change the original array: change

let arr = [6,8,10,12]; 
console.log(arr.reverse());//[12, 10, 8, 6]

sort() array sorting

Sort the elements of the array (the default is to sort from small to large and to sort according to strings)

Parameters: optional (function) specifies the sorting rules, the default sorting order is ascending alphabetically

Return value: new sorted array

Whether to change the original array: change

let arr = [32,44,23,54,90,12,9]; 
arr.sort(function(a,b){        
// return a-b;  // 结果[9, 12, 23, 32, 44, 54, 90]
// return b-a;  // 结果[90, 54, 44, 32, 23, 12, 9]   
})  
console.log(arr);

Array deduplication

let arr = ['a','b','c','a'];
// set 用于数组去重,成员是唯一的,不可以重复
let  newArr = [...new Set(arr)];
console.log(newArr);   // ['a', 'b', 'c']
let arr = ['a','b','c','a'];
let newArr = Array.from(new Set(arr));
console.log(newArr); // ['a', 'b', 'c']
let arr = ['a','b','c','a'];
let newArr = [];
for(var i = 0; i < arr.length; i++) {
    // indexOf()方法返回在数组中找到给定元素的第一个索引,若不存在,返回 -1
    // 判断是否在newArr数组中存在  1是存在,-1是不存在
    if(newArr.indexOf(arr[i]) == -1) {
      // push() 方法可向数组的末尾添加一个或多个元素,并返回新的长度。
      // 如果不存在,就追加到newArr里
        newArr.push(arr[i]);
    }
}
console.log(newArr)   // ['a', 'b', 'c']
let arr = ['a','b','c','a'];
let newArr = [];
arr.forEach(item => {
    // item 代表arr数组里的每一项
    if(newArr.indexOf(item) == -1)
    newArr.push(item);
})
cosnole.log(newArr);  // ['a', 'b', 'c']
let arr = ['a','b','c','a'];
let newArr = [];
arr.forEach(item => {
    // includes()方法用于判断字符串是否包含指定的子字符串,有则返回true,无则返回false;includes() 方法区分大小写。
    if(!newArr.includes(item))
    newArr.push(item);
})
console.log(newArr);  // ['a', 'b', 'c']

3. String method

All string methods return new strings. They do not modify the original string;

字符串是不可变的:字符串不能更改,只能替换

length()

作用:获取字符串长度

参数:无

返回:返回字符串长度

let str = 'hello';0
console.log(str.length())    //5

concat()

作用:用于将一个或多个字符串拼接起来

参数:可以有多个,用来拼接到str上的字符串

返回:返回拼接后的新字符串

let str = 'hello';
console.log(str.concat(' ' , 'world')) //'hello world'

slice()

作用:此方法用来提取一个字符串

参数:

1.beginIndex,表示从该索引处开始提取字符串的字符(包括),如果为负数则从后开始计算;

2.endIndex,表示从该索引处结束提取字符串(不包括),如果省略则一直提取到字符串末尾,如果为负数从后开始计算

返回:返回一个新的字符串

let str = 'hello world';
console.log(str.slice(6)) //'world'
console.log(str.slice(-5,-3)) //'wo'

substr(开始下标, 截取长度)

作用:截取字符串

参数:1.开始下标;2.截取长度

返回:截取出来的字符串(包括下标那个字符)

let str = "Hello world!";
let res = str.substr(6,5);
console.log(res)   // world

substring(开始下标, 结束下标)

作用:此方法和slice方法功能相同都是提取一个字符串

参数:1.开始下标(包括);2.结束下标(不包括)

上述两个参数:如果为负数或者NaN则都会被当做0,

如果大于字符串的长度则会被当做字符串的长度来计算,

如果 startIndex 大于 endIndex,则 substring 的执行效果就像两个参数调换了一样

返回:提取到的字符串

let str = 'hello world';
console.log(str.substring(-1,5))  //'hello'
console.log(str.substring(5,-1))  //'hello'

trim()

作用:删除一个字符串两端的空白字符

参数:无

返回:删除后的新字符串,不会改变原有字符串

toLowerCase()

作用:字符串值转为小写形式

参数:无

返回:转换后的字符串

toUpperCase()

作用:字符串值转为大写形式

参数:无

返回:转换后的字符串

replace(被替换部分, 新内容)

作用:可以将一个替换值替换字符串的一部分 (对大小写敏感)

参数:(二选一)

1.一个字符串中要被替换的子字符串或者正则表达式,默认值替换第一个,可以在正则表达式中设置全局模式,来替换所有匹配的子字符串;

2.一个替换值

返回:转换后的字符串

let str = "Hello world!";
let n = str.replace("world", "js");
console.log(n)   //Hello js!

let str = "Hello world!";
let m = str.replace(/WORLD/i, "js");   //注意正则表达式不带引号
console.log(m)   //Hello js!

split()

作用:可以使用一个指定的分隔符来将字符串拆分成数组

参数:

1.分隔符,可以为一个字符串也可以为正则表达式,为空的话则将每个字符都拆分。默认全局拆分;

2.拆分的长度(可选),为一个整数用来限制拆分的个数,如果超过了这个数量则新数组中不返回剩下的文本

返回:返回一个数组

//可以指定保留数组中几个元素:字符串.split(分隔符, 保留的个数)
let str = 'hello world';
console.log(str.split(" ")) //["hello", "world"]

charAt()

作用:从一个字符串中返回指定的字符

参数:index,介于0~length-1之间的整数,默认为0

返回:指定的字符

let str = 'hello world';
console.log(str.charAt(1)) //'e'

charCodeAt(下标)

作用:通过下标获取到对应字符的10进制的阿斯克码

参数:下标

返回:-

fromCharCode(阿斯克码)

作用:判断字符串中是否包含指定字符,包含则返回true,不包含则返回false

参数:ASCII码

返回:返回阿斯克码对应的字符

includes()

作用:判断字符串中是否包含指定字符,包含则返回true,不包含则返回false

参数:指定的字符串

返回:-

let str = 'hello world';
console.log(str.includes('hello')) //true
console.log(str.includes('fire')) //flase

indexOf()

作用:返回字符串中指定字符首次出现的下标,如果找不到则返回-1

参数:1.字符;2.开始下标(可选)

返回:-

let str = 'hello world, hello world';
console.log(str.indexOf('world')) //6
console.log(str.indexOf('sumshine')) //-1

lastIndexOf()

作用:用法和indexOf基本相同,区别是lastIndexOf()是从后往前查找

参数:1.字符;2.开始下标(可选)

返回:-

let str = 'hello sumshine, hello sumshine';
console.log(str.lastIndexOf('sumshine')) //22
console.log(str.lastIndexOf('world')) //-1

search()

作用:搜索特定值的字符串,并返回第一次匹配的下标,没有找到则返回-1;

参数:(二选一)

1.字符;

2.一个正则表达式,如果传入一个非正则表达式则会隐式的将其转换为正则表达式对象

返回:-

let str = 'hello world';
console.log(str.search('world')) //6
console.log(str.search(/w/)) //6

match(regexp)

作用:返回一个字符串匹配正则表达式的结果,如果未设置全局匹配,则会返回第一个完整匹配及其相关的捕获组,捕获组中包含有groups、index、input等属性

参数:一个正则表达式,如果传入一个非正则表达式则会隐式的将其转换为正则表达式对象

返回:-

//match(regexp) //select integers only
    let intRegex = /[0-9 -()+]+$/; 
    let myNumber = '999';
    let myInt = myNumber.match(intRegex);
    console.log(isInt);
    //output: 999
     
    let myString = '999 JS Coders';
    let myInt = myString.match(intRegex);
    console.log(isInt);
    //output: null

startsWith()

作用:函数检查字符串是否以指定的字符串或字符开始

参数:指定的字符串

返回:布尔值

let mystr = "List of javascript functions";
let n = mystr.startsWith("List");   //output: True

endsWith()

作用:函数检查字符串是否以指定的字符串或字符结束

参数:指定的字符串

返回:布尔值

let mystr = "List of javascript functions";
let n = mystr.endsWith("functions");   //output: True

repeat()

作用:构造并返回一个新字符串,该字符串包含被连接在一起的指定数量的字符串的副本

参数:数值

返回:-

let string = "Welcome to Edureka";
string.repeat(2);   //output: Welcome to Edureka Welcome to Edureka

valueOf()

作用:方法返回一个String对象的原始值(primitive value),该值等同于String.prototype.toString()

参数:-

返回:-

let mystr = "Hello World!";
let res = mystr.valueOf();   //output: Hello World!

padStart()

作用:从字符串的开头用另一个字符串填充一个字符串到一定长度

参数:1.填充后的字符串的长度;2.要填充的内容

返回:返回一个达到一定长度的结果字符串

例子1:
let str = '1234'.padStart(8,'0');
console.log(str); // "00001234"

例子2:第二个参数不传,就默认使用空格符填充
let str = 'abc'.padStart(5);
console.log(str); // "  abc"

例子3:结果字符串的长度必须为 5,因此,填充字符串被截断 ("f"),仅填充其最左边的部分 ("de")
str = "abc".padStart(5, "def");
console.log(str); // "deabc"

padEnd()

作用:从字符串的结尾用另一个字符串填充一个字符串到一定长度

参数:1.填充后的字符串的长度;2.要填充的内容

返回:返回一个达到一定长度的结果字符串

例子1:
str = 'abc'.padEnd(5,'*');
console.log(str); // "abc**"

例子2:第二个参数不传,就默认使用空格符填充
let str = 'abc'.padEnd(5);
console.log(str); // "abc  "

例子3:结果字符串的长度必须为 5,因此,填充字符串被截断 ("f"),仅填充其最左边的部分 ("de")
str = 'abc'.padEnd(5,'def');
console.log(str); // "abcde"

Guess you like

Origin blog.csdn.net/XiaoSen125_/article/details/128625081