当前位置:网站首页>Methods and extensions of array objects, extension methods of strings, and traversal of arrays in ES6
Methods and extensions of array objects, extension methods of strings, and traversal of arrays in ES6
2022-07-18 14:31:00 【Bald mule】
Catalog
2.startsWith and endsWith usage
3.repeat Number of string repetitions
1.for of Traversing the values of an array
One 、Array Object methods
1.Array.from()
Convert a pseudo array or traversable object to a real array ( character string , object , An array of class ,set,map etc. )
let str = '1234';
const arr1 =Array.from(str);
console.log(arr1);//(4) ['1', '2', '3', '4']
const Arr = {
2:'a',
3:'b',
length:4,
}
console.log(Array.from(Arr));// (4) [undefined, undefined, 'a', 'b']2.array.find()
Return the value of the first element of the array that meets the condition ( Arrays and objects )
const arr = [1,2,3,4];// Array
let num = arr.find(item=>item==3);
console.log(num);//3
const arr1 = [ // object
{realname:" Zhang San 1",age:18},
{realname:" Zhang San 2",age:17},
{realname:" Zhang San 3",age:19},
{realname:" Zhang San 4",age:17},
];
console.log(arr1.find(item=>item.age==17));//age: 17 realname: " Zhang San 2"3.array.findindex()
Find out the position of the qualified members .
const arr = [1,2,3,4]; // Array
console.log(arr.findIndex(item=>item==4)); //3
const arrobj = [ // object
{realname:" Zhang San 1",age:18},
{realname:" Zhang San 2",age:19},
{realname:" Zhang San 3",age:15},
{realname:" Zhang San 4",age:14},
]
console.log(arrobj.findIndex(item=>item.age==19)); //14.array.includes()
Find out whether an array contains a given value .
const arr = [1,2,3,4];
console.log(arr.includes(10));// Go back when you have true Return on no falseTwo 、Array Expand
1.array.map()
Return a new array
const arr = [1,2,3,4];
const newarr = arr.map(item=>item+2);
console.log(newarr); // Output an array again , Not changing the original array 2. array.filter()
Filter
const arr = [1,2,3,4,5,6,7];
const newarr = arr.filter(item=> item%2==0);
console.log(newarr);3.array.reduce()
cut
//total: It is both the initial value and the return value
//currentValue: Current value
reduce The second parameter specifies the initial value
const arr = [1,2,3,4,5];
let sum = arr.reduce((total,currentValue)=>{
return total + currentValue;
},10) // You can specify the initial value
console.log(sum);4.array.fill()
fill
let arr = [1,2,3,4,5,6,7];
arr.fill('x',1,3);
console.log(arr);//[1, 'x', 'x', 4, 5, 6, 7]3、 ... and 、string Expand
1. Template string usage
function demo(){
return "end";
}
let es6 = "es6!";
let str = `hello,${es6},${demo()}`;
console.log(str);//hello,es6,end2.startsWith and endsWith usage
let str = "hello,es6!";
console.log(str.startsWith("hello"));// Judge whether a string is preceded by hello If there is, it is true
console.log(str.endsWith("es6!"));// Judge whether a string contains es6 If there is, it is true3.repeat Number of string repetitions
console.log("hello".repeat(4));//hellohellohellohelloFour 、 Traversal of array
1.for of Traversing the values of an array
const arr = ["a","b","c","d"];
for(v of arr){
console.log(v); //a,b,c,d
}2.for in Traverse index
const arr = ["a","b","c","d"];
for(let k in arr){
console.log(k); //0,1,2,3
}3.for of Traversing objects
const Person={realname:'zs',age:20}
const keys = Object.keys(Person);
for(let k of keys){
console.log(`k:${k}`,`v:${Person[k]}`)}; //k:realname v:zs k:age v:204.forEach Usage of
let arr = [1,2,3,4];
arr.forEach((item,index)=>{
console.log(`v:${item},k:${index}`);
}) //v:1,k:0 v:2,k:1 v:3,k:2 v:4,k:3Example
1. Find the first student in a group who has passed the exam and output it to the page
<ul class="score"></ul>
<hr>
<h1 class="username"></h1>
<script>
let person=[
{realname:' Zhang San ',score:'40'},
{realname:' Li Si ',score:'40'},
{realname:' Wang Wu ',score:'60'},
{realname:' Zhao Liu ',score:'90'}
]
let str = '';
let userName='';
for(i=0;i<person.length;i++){
str = str + `<li> full name :${person[i].realname}, fraction :${person[i].score}</li>`
}
document.querySelector('.score').innerHTML=str;
userName = person.find(item=>item.score>=60)
document.querySelector('.username').innerHTML=` full name :${userName.realname}, fraction :${userName.score}`
</script>2. Find out if you are older than the specified age ( page input Box receive ) The first person , And output the location of this person
<ul class="age"></ul>
<hr>
<input type="text" placeholder=" Please enter age " value="" class="mark">
<input type="button" value=" Inquire about " class="btn">
<h1></h1>
<script>
let person=[
{realname:' Zhang San ',age:'15'},
{realname:' Li Si ',age:'18'},
{realname:' Wang Wu ',age:'19'},
{realname:' Zhao Liu ',age:'20'}
]
let str = '';
for(i=0;i<person.length;i++){
str = str + `<li> full name :${person[i].realname}, fraction :${person[i].age}</li>`
}
document.querySelector('.age').innerHTML=str;
btn = document.querySelector('.btn')
btn.onclick=function(){
let num;
input=document.querySelector('.mark').value;// Get the entered value
num = person.findIndex(item=>item.age==input)// Get the subscript
if(num==-1){
document.querySelector('h1').innerHTML=' Check no one ';
}else{
num++;
document.querySelector('h1').innerHTML=` Location is ${num}`
}
}
</script>3. Output a set of personnel information , The information output to the page is as follows ( full name , fraction , Pass or not 60 branch )
const person=[
{realname:'zs1',age:20,score:50},
{realname:'zs2',age:20,score:70},
{realname:'zs3',age:20,score:80},
{realname:'zs4',age:20,score:90}
]
// Use for of Display content on Web pages
// let arr='';
// for(let v of person){
// arr =arr+ `<li> full name :${v.realname}, Age :${v.age}</li>`
// }
// document.querySelector('ul').innerHTML=arr;
let mark='';
let newarr = person.filter(item=>{
let rer= item.score>60?' pass ':' fail, '
mark+=`<li> full name :${item.realname}, Age :${item.age}, fraction :${item.score},${rer}</li>`
})
document.querySelector('ul').innerHTML=mark;边栏推荐
- Points clés pour la mise à niveau du firmware d'aegnus air820ug
- HMS Core图形图像技术展现最新功能和应用场景,加速构建数智生活
- 函数关系简
- 基于单片机的蓝牙电子秤系统设计(#0493)
- In depth learning (2020 Li Hongyi) learning records
- Solve the problem of Vue multi-level route cache invalidation solve the problem of multi-level route cache based on keep alive Vue keep alive cache invalidation Vue element admin multi-level route cac
- Summary of ES interview questions - > Chapter 6
- STM32通用定时器
- Signal函数大全:
- LeetCode:735. Planetary collision - medium
猜你喜欢
随机推荐
[phantom engine UE] package abnormal problem collection
XGBoostError: [10:19:14] C:\dev\libs\xgboost\src\objective\objective. cc:23:
Gd32f4xx IAP upgrade ideas
Clear the temporary table and check the memory occupied by the temporary table
【Leetcode】2115. Find All Possible Recipes from Given Supplies
NXOpen UG二次开发
What if win11 prompts outlook for search errors? Win11 prompt outlook search error
合宙Air820ug升级固件要点
XGBoostError: [10:19:14] C:\dev\libs\xgboost\src\objective\objective.cc:23:
C&W(Carlini & Wagner)
Codeforces Round #803 (Div. 2) B. Rising Sand
[atlas quick start]
[the most complete and detailed] seven distributed global ID generation strategies
汇编基础-CTF
[gbase] modify the varchar length of the field
第一章 环境配置
Have you used useeffect and uselayouteffect
Translation embeddings for modeling multi relational data [transce]
HMS Core图形图像技术展现最新功能和应用场景,加速构建数智生活
Huawei cloud stack opens its framework to the south to help ecological partners enter the cloud efficiently

![[AI chip Caisa]](/img/01/b216532a7b2d5cc1af4b98991fefac.png)






![[edge deployment AI]](/img/6c/32f9a97df5624f5a20d133d76e7a6f.png)