当前位置:网站首页>Summary of common methods and attributes of arrays and strings in JS
Summary of common methods and attributes of arrays and strings in JS
2022-07-27 21:14:00 【Xiaomenong】
js Summary of common methods and attributes of arrays and strings in
String Object properties
| attribute | describe |
|---|---|
| length | Length of string |
| prototype | Allows you to add properties and methods to an object |
length
length: Length of character creation
<script>
var str = "Hello World!";
document.write(txt.length);
</script>
result :12
String Object methods
| attribute | describe |
|---|---|
| charAt() | Returns the character in the specified position . |
| charCodeAt() | Returns the... Of a character in a specified position Unicode code . |
| concat() | Connect two or more strings , And return the new string . |
| endsWith() | Determines whether the current string ends with the specified substring ( Case sensitive ). |
| fromCharCode() | take Unicode Code to character . |
| indexOf() | Returns the first occurrence of a specified string value in a string . |
| includes() | Find if the string contains the specified substring . |
| lastIndexOf() | Search string from back to front , And from the beginning (0) Start calculating the last occurrence of the return string . |
| match() | Find a match for one or more regular expressions . |
| repeat() | Copy string specified number of times , And connect them back together . |
| replace() | Find the matching substring in the string , And replace the substring that matches the regular expression . |
| replaceAll() | Find the matching substring in the string , And replace all substrings that match the regular expression . |
| search() | Find the value that matches the regular expression . |
| slice() | Extract a fragment of a string , And return the extracted part in the new string . |
| split() | Split a string into an array of strings . |
| startsWith() | See if the string starts with the specified substring . |
| substr() | Extract the specified number of characters in the string from the starting index number . |
| substring() | Extract the character between two specified index marks in the string . |
| toLowerCase() | Convert string to lowercase . |
| toUpperCase() | Convert strings to uppercase . |
| trim() | Remove the white space on both sides of the string . |
| toLocaleLowerCase() | Convert strings to lowercase according to the locale of the local host . |
| toLocaleUpperCase() | Convert strings to uppercase based on the locale of the local host . |
| valueOf() | Returns the original value of a string object . |
| toString() | Returns a string . |
chartAt()
chartAt() Returns the character in the specified position
var str = "HELLO WORLD";
var n = str.charAt(2);
console.log(n)
result :L
concat()
concat() Connect two or more strings
function myFunction(){
var txt1 = "Hello ";
var txt2 = "world!";
var txt3="NI HAO";
var n=txt1.concat(txt2,txt3);
document.getElementById("demo").innerHTML=n;
}
</script>
result :Hello world!NI HAO
endsWith()
endsWith() Judge whether the current string ends with the specified string
let str = "Hello world";
str.endsWith("world") // return true
str.endsWith("World") // return false
startsWith()
startsWith() Judge whether the current string starts with the specified string
var str = "Hello world, welcome to the Runoob.";
var n = str.startsWith("Hello");
result :true
indexOf()
indexOf() Returns the first occurrence of a string in this string , If not found, put it back false
var str="Hello world";
var n=str.indexOf("world");
result :6
repeat()
repeat() Copy string specified number of times , And connect them back together
var str = "Runoob";
str.repeat(2);
result :RunoobRunoob
replace()
replace() Find the matching substring in the string , And replace the matching substring . In this case , We will perform a replacement , When the first one “Microsoft” Found , It is replaced by “Runoob”:
var str="Visit Microsoft! Visit Microsoft!";
var n=str.replace("Microsoft","Runoob");
result :Visit Runoob!Visit Microsoft!
replaceAll()
replaceAll() Find the matching substring in the string , And replace all matching substrings .. In this case , We will perform a replacement , Find all “Microsoft” , Replace with “Runoob”:
var str="Visit Microsoft! Visit Microsoft!";
var n=str.replaceAll("Microsoft","Runoob");
result :Visit Runoob!Visit Runoob!
serach()
serach() Find the value that matches the regular expression .
var str="Visit Runoob!";
var n=str.search("Runoob");
result :6
// Perform a case sensitive lookup :
var str="Mr. Blue has a blue house";
document.write(str.search("blue"));
// result :15
// Perform a case insensitive Retrieval :
var str="Mr. Blue has a blue house";
document.write(str.search(/blue/i));
// result :4
slice()
slice(start,end) Intercepting string Return the extracted part in the new string
start: Start with the number of bits in the string
end: To the end of the string ( barring end)
var str="Hello world!";
var n=str.slice(1,5);
// result :ello
// Extract all strings :
var str="Hello world!";
var n=str.slice(0);
// result :Hello world!
// From the first... Of the string 3 Extract the string fragment at three positions :
var str="Hello world!";
var n=str.slice(3);
//lo world!
// From the first... Of the string 3 Position to 8 A direct string fragment :
var str="Hello world!";
var n=str.slice(3,8);
result :lo wo( Note that the last one is not included )
// Extract the last character and the last two characters
var str="Hello world!";
var n=str.slice(-1);
var n2=str.slice(-2);
// result !
// result d!
split()
split() Split a string into an array of strings .
Divide a string into an array of strings : Note that the middle is separated by a space
var str="How are you doing today?";
var n=str.split(" ");
// result :How,are,you,doing,today?
// Split each character , Including Spaces :
var str="How are you doing today?";
var n=str.split("");
// result :H,o,w, ,a,r,e, ,y,o,u, ,d,o,i,n,g, ,t,o,d,a,y,?
// Use limit Parameters :
var str="How are you doing today?";
var n=str.split(" ",3);
// result :How,are,you
// Use a character as a separator :
var str="How are you doing today?";
var n=str.split("o");
// result :H,w are y,u d,ing t,day?
substr()
substr(1,2) Intercepts a specified number of characters , The first parameter is the number of characters , The second parameter is to intercept several characters
// Extract a specified number of characters :
var str="Hello world!";
var n=str.substr(2,3)
// result :llo
// In this case , We will use substr() Extract some characters from the second position of the string :
var str="Hello world!";
var n=str.substr(2)
// result :llo world!
substring()
substring(1,2) Intercepts a specified number of characters , The first parameter is the number of characters , The second parameter is the cut-off, and the number of parameters ends , Note that the last one is not included
// Extract a specified number of characters :
var str="Hello world!";
var n=str.substr(2,3)
// result :l
toLowerCase()
toLowerCase() : String to lowercase
toUpperCase()
toUpperCase(): String to uppercase .
trim ()
trim () : Except for the blank space on both sides of the string .
toString ()
toString () : Returns a string .
Aarry
| attribute | describe |
|---|---|
| length | Sets or returns the number of array elements . |
Aarry.length
length
var fruits = ["1", "d", "f", "h"];
console.log(fruits.length);
result :4
Array Object methods
| attribute | describe |
|---|---|
| concat() | Two or more arrays , And return the result . |
| copyWithin() | Copy elements from the specified location of the array to another specified location of the array . |
| entries() | Returns the iteratable object of the array . |
| every() | Checks whether each element of a numeric element is eligible . |
| fill() | Fill the array with a fixed value . |
| filter() | Detect value elements , And returns an array of all elements that meet the criteria . |
| find() | Return compliance with incoming test ( function ) Conditional array elements . |
| findIndex() | Return compliance with incoming test ( function ) Conditional array element index . |
| forEach() | Each element of the array performs a callback function . |
| from() | Create an array from the given object . |
| includes() | Determine whether an array contains a specified value . |
| indexOf() | Search for elements in the array , And return to where it is . |
| isArray() | Determine whether the object is an array . |
| join() | Put all the elements of the array into a string . |
| keys() | Returns the iteratable object of the array , Contains the key of the original array (key). |
| lastIndexOf() | Search for elements in the array , And return to where it last appeared . |
| map() | Handle each element of the array by specifying a function , And return the processed array . |
| pop() | Delete the last element of the array and return the deleted element . |
| push() | Add one or more elements... To the end of the array , And returns the new length . |
| reduce() | Evaluate an array element to a value ( From left to right ). |
| reduceRight() | Evaluate an array element to a value ( From right to left ). |
| reverse() | Reverse the order of elements in an array . |
| shift() | Delete and return the first element of the array . |
| slice() | Pick a part of the array , And return a new array . |
| some() | Check whether any element in the array element meets the specified conditions . |
| sort() | Sort elements of an array . |
| splice() | Add or remove elements from an array . |
| toString() | Convert an array to a string , And return the result . |
| unshift() | Add one or more elements to the beginning of an array , And returns the new length . |
| valueOf() | Returns the original value of the array object . |
concat()
concat(arry): Concatenate two arrays
function myFunction(){
var arr1= [1,2,3,4]
var arr2= ["a","b"];
var arr3=[6,7];
arr1.concat(arr2,arr3)
}
</script>
result :1,2,3,4,a,b,6,7
copyWithin()
Copy elements from the specified location of the array to another specified location of the array
Parameters ---------------- describe
target-------------- It's necessary . Copy to the specified target index location .
start---------------- Optional . The starting point of element copying .
end------------------ Optional . Stop copying index location ( The default is array.length). If it's negative , Said the bottom .
var fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi", "Papaya"];
fruits.copyWithin(2, 0, 2);
j result :Banana,Orange,Banana,Orange,Kiwi,Papaya
entries()
entries() Method returns the iterated object of an array , This object contains the key value pairs of the array (key/value). Is to change the object you create into key And value In the form of
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.entries();
result :
[0, “Banana”]
[1, “Orange”]
[2, “Apple”]
[3, “Mango”]
every()
every(): Check whether all elements of the array meet the conditions
var ages = [32, 33, 16, 40];
function checkAdult(age) {
return age >= 18;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.every(checkAdult);
}
result :false
fill()
fill(): Fill the array with a fixed value .
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.fill("Runoob");
result :Runoob,Runoob,Runoob,Runoob
filter()
filter(): Detect value elements , And returns an array of all elements that meet the criteria .
var ages = [32, 33, 16, 40];
function checkAdult(age) {
return age >= 18;
}
console.log(ages.filter(checkAdult))
result :32,33,40
find()
find(): Return compliance with incoming test ( function ) Conditional array elements .
var ages = [3, 10, 18, 20];
function checkAdult(age) {
return age >= 18;
}
console.log(ages.find(checkAdult))
result :18
findIndex()
findIndex(): Get the index position of the first element in the array that meets the condition
var ages = [3, 10, 18, 20];
function checkAdult(age) {
return age >= 18;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.findIndex(checkAdult);
}
result :2
forEach()
forEach(): Loop traversal
numbers.forEach(myFunction)
from()
from(): Create an array from the given object
var arr = Array.from([1, 2, 3], x => x * 10);
// arr[0] == 10;
// arr[1] == 20;
// arr[2] == 30;
includes()
includes(): Determine whether an array contains a specified value .
let site = ['runoob', 'google', 'taobao'];
site.includes('runoob');
// true
site.includes('baidu');
// false
indexOf()
indexOf() Search for elements in the array , And return to where it is .
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var a = fruits.indexOf("Apple");``` ** result :2** # isArray() >isArray(): Determine whether the object is an array ```javascript
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = Array.isArray(fruits);
result :true
join()
join(): Put all the elements of the array into a string .
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var energy = fruits.join();
result :Banana,Orange,Apple,Mango
lastIndexOf()
lastIndexOf(): Find the position of an element in the array element
var fruits=[" Banana "," The oranges "," Apple "," melon "];
var a=fruits.lastIndexOf(" Apple ")
console.log(a)
result :true
map()
map(): Handle each element of the array by specifying a function , And return the processed array .
// Returns an array , The elements in the array are the square root of the original array :
var numbers = [4, 9, 16, 25];
var a=numbers.map(Math.sqrt);
console.log(a)
result :2,3,4,5
pop()
pop(): Delete the last element of the array and return the deleted element
push()
push(): Add one or more elements... To the end of the array , And returns the new length .
reduce()
reduce(): Evaluate an array element to a value ( From left to right ).
reduceRight()
reduceRight(): Evaluate an array element to a value ( From right to left ).
shift()
shift() : Delete and return the first element of the array .
slice()
slice(): Pick a part of the array , And return a new array .
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var myBest = fruits.slice(-3,-1); // Intercept the penultimate ( contain ) To the last one ( It doesn't contain ) Two elements of
var myBest = fruits.slice(-3); // Intercept the last three elements
result :Lemon,Apple
some()
some(): Check whether any element in the array element meets the specified conditions .
var ages = [3, 10, 18, 20];
function checkAdult(age) {
return age >= 18;
}
console.log(ages.some(checkAdult));
sort()
sort()L: Sort elements of an array
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
splice()
splice(): Add or remove elements from an array .
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2,0,"Lemon","Kiwi");
//Banana,Orange,Lemon,Kiwi,Apple,Mango
// Remove the third element of the array , And add a new element in the third position of the array :
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2,1,"Lemon","Kiwi");
//Banana,Orange,Lemon,Kiwi,Mango
// Starting from the third position, delete the two elements after the array :
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2,2);
//Banana,Orange
toString()
toString(): Array to string :
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.toString();
result :Banana,Orange,Apple,Mango
unshift()
unshift(): Add one or more elements to the beginning of an array , And returns the new length .
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon","Pineapple");
result :Lemon,Pineapple,Banana,Orange,Apple,Mango
valueOf()
valueOf(): Returns the original value of the array object
边栏推荐
- Win11 widget prompts how to solve the error when loading this content?
- MapGIS三维场景渲染技术与应用
- Overview of understanding the physical layer of transmission media
- Stick to one thing
- Leetcode daily practice - the penultimate node in the linked list
- Win11小组件提示加载此内容时出现错误怎么解决?
- Differences among native objects, built-in objects, and host objects
- Uncaught SyntaxError: redeclaration of let page
- Know the transmission medium, the medium of network communication
- Understand the communication mode of transmission media
猜你喜欢

一文读懂Plato&nbsp;Farm的ePLATO,以及其高溢价缘由

Feixin died in 2022: a good hand of China Mobile was broken, and 500million users became "zombies"

Leetcode-209- subarray with the smallest length

Smart Internet ran out of China's "acceleration", and the market reshuffle behind the 26.15% carrying rate

Win11系统更新KB5014668后点开始按钮没反应怎么办?

自动化测试----unittest框架

Rust变量特点

飞信卒于2022:中国移动一手好牌被打烂,5亿用户成“僵尸”

API Gateway介绍

自动化测试----selenium(二)
随机推荐
智能网联跑出中国「加速度」,26.15%搭载率背后的市场洗牌
Airiot Q & A issue 6 | how to use the secondary development engine?
R language dplyr package summary_ The at function calculates the count number, mean and median of multiple data columns (specified by vectors) in the dataframe data, and specifies the function list us
力扣 919. 完全二叉树插入器
PHP代码审计5—XSS漏洞
User login switching case
Elk too heavy? Try KFC log collection
数字引领 规划先行 聚焦智慧规划信息平台建设及应用项目探索实践
论文赏析[EMNLP18]针对自顶向下和中序移进归约成分句法分析的Dynamic Oracles
Codeforces 1706e merge + heuristic merge + st table
What are the application scenarios of real name authentication in the cultural tourism industry?
QT link MSSQL
数字化工厂管理系统有哪些价值
Knife4j dynamically refreshes global parameters through JS
One of IOU target tracking: IOU tracker
How to make personalized recommendations instantly accessible? Cloud native database gaussdb (for redis) to help
Win11小组件提示加载此内容时出现错误怎么解决?
【历史上的今天】7 月 27 日:模型检测先驱出生;微软收购 QDOS;第一张激光照排的中文报纸
DJI push code (one code for one use, updated on July 26, 2022)
如何对话CIO/CTO