JavaScript--common array and string methods

Source: Internet
Author: User
Tags array length string methods

Array
var arr= new Array();arr.push();     //在数组尾部添加一个元素,返回新的长度     *原数组发生变化arr.pop();      //删除最后一个元素,返回的是被删除的元素    *原数组发生变化arr.unshift();      //在头部添加一个元素,返回长度      *原数组发生变化arr.shift();        //删除数组第一个元素,返回被删除的元素  *原数组发生变化arr.concat();     //添加元素或数组,返回一个一维数组,可用来合并数组arr.join();     //将数组内的元素用()内的符号连接起来返回一个字符串arr.reverse();      //颠倒数组中的元素              *原数组发生变化arr.sort();     //将数组元素排序,如果调用该方法时没有使用参数,将按字母顺序对数组中的元素进行排序  *原变arr.slice(x,y);     //  返回数组中的一部分,根据下标,前包后不包 arr.splice();//例arr.splice(x);    //数组保留x位,其余的删除arr.splice(2,0,100);  //在arr第2个元素后面,删除0个,插入100,返回的是被删除的元素

ES6 New

(1) Copying an array

// 写法一const a2 = [...a1];// 写法二const [...a2] = a1;

(2) Merging arrays

// ES5[1, 2].concat(more)// ES6[1, 2, ...more]

(3) string

The extension operator can also convert a string to a true array.

[...‘hello‘]// [ "h", "e", "l", "l", "o" ]

The array.of method is used to convert a set of values into an array

Array.of can basically be used to replace array () or new array (), and there are no overloads that result from different parameters. Its behavior is very uniform.

Array.of(3, 11, 8) // [3,11,8]

Copywithin Copies the members of the specified position to a different location (overwriting the original member) inside the current array, and then returns the current array. In other words, using this method modifies the current array.

[1, 2, 3, 4, 5].copyWithin(0, 3)// [4, 5, 3, 4, 5]// -2相当于3号位,-1相当于4号位[1, 2, 3, 4, 5].copyWithin(0, -2, -1)// [4, 2, 3, 4, 5]

Find,findindex

A method of an array instance that is find used to find the first qualifying array member. Its argument is a callback function, in which all array members execute the callback function sequentially until they find the first member to return a value of true, and then return the member. If there are no eligible members, the undefined is returned.

[1, 4, -5, 10].find((n) => n < 0)   //-5[1, 5, 10, 15].find(function(value, index, arr) {  return value > 9;}) // 10

In addition, both methods can find Nan, which makes up for the insufficiency of the IndexOf method of the array.

[NaN].indexOf(NaN)// -1[NaN].findIndex(y => Object.is(NaN, y))// 0

fill fills an array with the given value.

[‘a‘, ‘b‘, ‘c‘].fill(7)// [7, 7, 7]new Array(3).fill(7)// [7, 7, 7]

The Fill method can also accept the second and third parameters, which specify the starting and ending positions of the fill.

[‘a‘, ‘b‘, ‘c‘].fill(7, 1, 2)// [‘a‘, 7, ‘c‘]

The method of an array instance is findIndex used very similarly to the Find method, returning the position of the first qualifying array member, or 1 if all members do not meet the criteria.

entries (), keys (), and values ()--for iterating over an array. They all return a Walker object that can be traversed with a for...of loop, the only difference being that keys () is the traversal of the key name, values () is the traversal of the key value, and entries () is the traversal of the key-value pair.

for (let index of [‘a‘, ‘b‘].keys()) {  console.log(index);}// 0// 1for (let elem of [‘a‘, ‘b‘].values()) {  console.log(elem);}// ‘a‘// ‘b‘for (let [index, elem] of [‘a‘, ‘b‘].entries()) {  console.log(index, elem);}// 0 "a"// 1 "b"

includes indicates whether a number group contains the given value

[1, 2, 3].includes(2)     // true[1, 2, 3].includes(4)     // false[1, 2, NaN].includes(NaN) // true

The second parameter of the method represents the starting position of the search, which defaults to 0. If the second argument is a negative number, it is the position of the reciprocal, and if it is larger than the array length (for example, the second argument is-4, but the array length is 3), it is reset to start at 0.

[1, 2, 3].includes(3, 3);  // false[1, 2, 3].includes(3, -1); // true
String
var str=new String("abvdefg");str.indexOf(‘abc‘);   //返回指定字符第一次出现的位置,没有返回-1str.lastIndexOf(‘w‘);    //返回指定字符最后一次出现的位置,没有返回-1str.slice(startIndex,endIndex);     //返回匹配到的字符串,前包后不包str.substr(startIndex,length);      //返回一个字符串str.charAt(x);      //返回指定索引位置的字符str.charCodeAt();   //返回在指定的位置的字符的 Unicode 编码。str.split();        //把字符串分割为字符串数组,()内可写正则表达式(‘‘)将每个元素按照数组中的每个元素分割str.toLowerCase();      //把字符串转换为小写。str.toUpperCase();      //把字符串转换为大写

ES6 New

//for...of字符串遍历器接口for(let item of str){    console.log(item)}str.includes(x)     //返回布尔值,表示是否找到了参数字符串。str.startsWith(x)       //返回布尔值,表示参数字符串是否在原字符串的头部。str.endsWith(x)     //返回布尔值,表示参数字符串是否在原字符串的尾部。这三个方法都支持第二个参数,表示开始搜索的位置,参数如果是小数,会被取整。。如:str.startsWith(‘f‘, 2) // true使用第二个参数x时,endsWith的行为与其他两个方法有所不同。它针对前x个字符,而其他两个方法针对从第x个位置直到字符串结束。str.repeat(x);      //返回一个新字符串,表示将原字符串重复x次。padStart(),padEnd如果某个字符串不够指定长度,会在头部或尾部补全,一共接受两个参数,第一个参数用来指定字符串的最小长度,第二个参数是用来补全的字符串。‘x‘.padStart(4, ‘ab‘) // ‘abax‘‘x‘.padEnd(5, ‘ab‘) // ‘xabab‘如果原字符串的长度,等于或大于指定的最小长度,则返回原字符串。‘xxx‘.padEnd(2, ‘ab‘) // ‘xxx‘如果省略第二个参数,默认使用空格补全长度。‘x‘.padStart(4) // ‘   x‘如果用来补全的字符串与原字符串,两者的长度之和超过了指定的最小长度,则会截去超出位数的补全字符串。‘abc‘.padStart(10, ‘0123456789‘)  //// ‘0123456abc‘另一个用途是提示字符串格式。‘12‘.padStart(10, ‘YYYY-MM-DD‘) // "YYYY-MM-12"‘09-12‘.padStart(10, ‘YYYY-MM-DD‘) // "YYYY-09-12"

JavaScript--common array and string methods

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.