Array extension
forEach
Format:
//The first parameter is the function //The first argument to the function is the current element being traversed //The second argument to the function is the subscript of the current element //The third element of the function is the array itself. //The second parameter is: this point in the function. arr.forEach(function(item,index,arr){ },obj);
var arr = [ "Spirited away", "The Shawshank Redemption", "Who fell in love with him first", "Hal's mobile Castle", "Marine pianist" ] var lis = document.querySelectorAll("li") arr.forEach(function(item,index,self){ // console.log("movie name:" + item + ", subscript:" + index "); console.log(this); //Five times NodeList(5) this[index].innerHTML = item;//Write the contents of the array to li },lis);
map method
The meaning of map mapping is basically similar to forEach.
You can define the return value in the function. The return is an array.
var arr = [ {name:"Spirited away",score:"8.6"}, {name:"The Shawshank Redemption",score:"9.6"}, {name:"Who fell in love with him first",score:"8.3"}, {name:"Hal's mobile Castle",score:"8.9"}, {name:"Marine pianist",score:"9.0"} ] var arr2 = arr.map(function(item){ return item.score; }); console.log(arr2);
Array.form()
Array. The form method can convert an object similar to an array into a real array. For example, the pseudo array obtained by DOM and the arguments object.
let lis = document.querySelectorAll("li"); console.log(lis);//NodeList(5) [li, li, li, li, li] var arr = Array.from(lis); console.log(arr);//(5) [li, li, li, li, li] function sort(){ var args = Array.from(arguments); return args.sort(); } console.log(sort(6,3,5));//(3) [3, 5, 6]
let likeArr = { length:3, "0":"hello", "1":"word", "2":"Hello" } let arr = Array.from(likeArr); console.log(arr);// ["hello", "word", "hello"]
Array.of()
Array. The of method converts a set of values into an array.
let arr = Array.of(1,2,3); console.log(arr); //Array(3) // 0: 1 // 1: 2 // 2: 3 // length: 3 let arr2 = new Array(3); console.log(arr2); //[empty × 3] The array is empty and the length is 3
copyWithin()
Copy the content of the specified location to another location (the copy will overwrite the original content), and then return the current array.
Format:
//target: required. Overwrite from this position //start: optional. start reading data from this location. The default value is 0. If it is negative, it means reciprocal. //End: optional to end reading data at this position. The default is the length of the array. If it is negative, it means reciprocal arr.copyWithin(target,[start],[end]){}
var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; //arr.copyWithin(3, 4) //[0, 1, 2, 4, 5, 6, 7, 8, 9, 9] //arr.copyWithin(3, 2) //[0, 1, 2, 2, 3, 4, 5, 6, 7, 8] arr.copyWithin(3, -1); //[0, 1, 2, 9, 4, 5, 6, 7, 8, 9] console.log(arr);
find() and findIndex()
Find method to find the first qualified array element.
arr.find(function(item,indedx,arr){ //Conditional judgment })
var arr = [1,6,-10,-9].find(function(item){ return item < 0; }) // ES6 arrow function writing method var arr = [1,6,-10,-9].find(item=>item < 0) console.log(arr);//2
findIndex, find the index of the first qualified array element.
var arr = [1,6,-10,-9].findIndex(item=>item < 0) console.log(arr);//-10
keys(),values(),entries()
These three methods are mainly used for array traversal. Cooperate with the for... of loop.
keys(): traversal of key names
values(): traversal of key values
entries(): traversal of key value pairs.
var arr = ["a", "b"] for (const item of arr.keys()) { console.log(item); //0 1 } for (const item of arr.values()) { console.log(item);//a b } for (const item of arr.entries()) { console.log(item); //(2) [0, "a"] (2) [1, "b"] }
for... of loop
//Format: //item refers to the current element traversed //arr refers to the traversal array for (const item of arr) { console.log(item); } var arr = ["a","b"] for (const item of arr) { console.log(item); }
var arr = ["a","b"] for (const item of arr.keys()) { console.log(item); } // 0 1 for (const item of arr.values()) { console.log(item); } // a b for (const item of arr.entries()) { console.log(item); } //[0,"a"] [1,"b"]
includes()
This method can determine whether the array contains the specified value.
Format:
//arr: array //Value: judge whether the array contains the value //target: search from the specified position of the array. arr.includes(value,target)
Return value: Boolean value: true is inclusive, false is not inclusive
console.log( [1,2,3].includes(2)); //true console.log( [1,2,3].includes("2")); //false console.log([1,2,3].includes(2,1));//true console.log([1,2,3].includes(2,2));//false
var arr = [1,2,3, NaN] var index = arr.indexOf(2); if(index !== -1){ console.log("The value already contains"); }else{ console.log("The value does not contain"); }//The value does not contain indexOf. NaN is not recognized
var arr = [1, 2, 3, NaN] console.log(arr.includes(NaN)); //true
The difference between the includes method and the indexOf() method
- indexOf returns a subscript. includes returns a Boolean value
- indexOf is used to judge whether the content is not semantic and intuitive enough.
- There are misjudgments about NaN.
Object extension method
Object.assign()
assign() is used to merge objects.
Format:
//All parameters after the first parameter are merged into the first parameter. Object.assign(target,obj1,obj2)
const target = {name:'Audrey Hepburn·Hepburn'} const obj1 = {age:'20'} const obj2 = {sex:'female'} Object.assign(target,obj1,obj2); console.log(target);
Shallow copy
Only the memory address of the composite data is copied. The copied variable still points to the original object.
Deep copy
A new object is generated. The values of the new object and the old object are exactly the same, and then the address of the new object is copied.
The assign method is a shallow copy. In other words, if an attribute of the merged object is an object, the memory address of the object will be copied from the target object.
Property with the same name
const obj1 = { name:"Audrey Hepburn", age:"20", son:{ name:"Luca·Dotty", age:"40" } } const obj2 = { name:"Hepburn" } const target = { name:"Audrey Hepburn·Hepburn", sex:"female" }; Object.assign(target,obj1,obj2); console.log(target);
If an attribute with the same name is encountered, the attribute in the subsequent parameter object will overwrite the previous attribute.
Used on arrays
When used on an array, the array is treated as an object.
var arr1 = [10,20,30]; // arr1 = { // "0":"a", // "1":"b", // "2":30 // } var arr2 = ["a","b"]; // arr2 = { // "0":"a", // "1":"b" // } Object.assign(arr1,arr2); console.log(arr1); //a,b,30
aggregate
1. What is a collection
1. Disorder
2. No repetition
2.Set
The new data structure of ES6 is similar to array, but the elements are unique and have no order.
Create set
let s = new Set();
Two ways to add elements
let s = new Set([30,40]); s.add(10) s.add(20)
let s = new Set([30,40]); s.add(10) s.add(20) s.add(10) s.add(true) s.add("10") s.add("10") s.add(new String("hello")); s.add(new String("hello")); console.log(s); //30,40,10,20,tue,"10",String,String
Properties and methods
size attribute
Returns the number of elements in the set collection.
set.size;
add(value)
Add an element to the set and return the set itself.
delete(value)
A Boolean value indicating whether the deletion was successful.
has(value)
Judge whether the specified value exists in set and return a Boolean value.
clear()
Clear all elements. no return value
supplement
Method of converting set to array
Array. The from method can convert a Set into an array.
const arr = Array.from(s);
rest parameter
const arr2 = [...s];
De duplication of array
var arr = [10,20,20,30,50,30];//10,20,30,50 var set = new Set(arr); arr = Array.from(set); console.log(arr); //A method of de duplication encapsulated into an array function noDupli(array){ return Array.from(new Set(array)); }
Traversal operation
keys()
Return key name traverser
values()
Iterator that returns the value of the key
entries()
Returns the traversal of key value pairs
for (const item of set.keys()) { console.log(item); } for (const item of set.values()) { console.log(item); } for (const item of set.entries()) { console.log(item); } for (const item of set){ console.log(item); }
3.Map
Is a collection of key value pairs. It is similar to the property and property value in the object, but the property name in the object can only be a string. Value – value correspondence, string – value correspondence.
Create Map
let map = new Map();
How to add elements
let map = new Map(); map.set("Zheng Shuang","TMD That's so annoying") map.set("Miss Ma","conduct oneself well") map.set("Luo Zhixiang","Nine o'clock tonight, multiplayer") let map = new Map([ ["name","Zhou Runfa"],["age","40"] ]);
Uniqueness
The uniqueness of the key, not the value.
let map = new Map(); map.set("Zheng Shuang","TMD That's so annoying") map.set("Miss Ma","conduct oneself well") map.set("Miss Ma","Young people don't talk about martial virtue") // map.set("Hunyuan Xingyi Taijiquan leader", "take care of yourself") map.set("Luo Zhixiang","Nine o'clock tonight, multiplayer")
Properties and methods
size
Returns the number of key value pairs in the map.
set(key,value)
Add a key value pair to the map set and return the map itself. If the key exists, the original value will be overwritten.
delete(key)
Find the corresponding key value pair through the key, delete it, and return a Boolean value to indicate whether the deletion is successful.
has(key)
Determines whether the specified key exists in the map and returns a Boolean value.
clear()
Clear all elements. no return value
get(key)
Read the key value corresponding to the key. If it cannot be found, return undefined
Traversal operation
keys()
Return key name traverser
values()
Iterator that returns the value of the key
entries()
Returns the traversal of key value pairs
Traversal method summary
<script> // array // for loop // for...in // foreach //for...of // object // for..in // set // for...of foreach // map var arr = [10, 20, 30, 40, 50]; for (let i = 0; i < arr.length; i++) { document.write("<p>for Loop: current element is:" + arr[i] + ",Subscript:" + i + "</p>"); } for (const key in arr) { document.write("<p>for...in: Subscript:" + key + "</p>"); } arr.forEach((item, index) => { document.write("<p>forEach Loop: current element is:" + item + ",Subscript:" + index + "</p>");; }) for (const item of arr) { document.write("<p>for...of Loop: current element is:" + item + "</p>");; } var obj = { name: "Zhou Runfa", age: "40", sex: "male" } for (const key in obj) { document.write("<p>Object traversal: the current property is:" + key + ",The attribute value is:" + obj[key] + "</p>"); } var set = new Set([10, 20, 30, 40, 50]); for (const item of set) { document.write("<p>set for...of Loop: current element is:" + item + "</p>");; } set.forEach(item => { document.write("<p>set foreach Loop: current element is:" + item + "</p>");; }); let map = new Map(); map.set("Miss Ma", "Young people don't talk about martial virtue") map.set("Hunyuan Xingyi Taijiquan leader", "conduct oneself well") map.set("Luo Zhixiang", "Nine o'clock tonight, multiplayer") for (const item of map.keys()) { document.write("<p>map for..of Traversal: the current key is:" + item + ",The value is:" + map.get(item) + "</p>"); } map.forEach((value, key) => { document.write("<p>map forEach Traversal: the current key is:" + key + ",The value is:" + value + "</p>"); }) </script>
Object extension
1. Concise representation of object attributes
ES6 can write variables and functions directly into the braces of the object as the attributes and methods of the object. If the attribute name is the same as the variable name, it can be abbreviated, just write the attribute name.
var name = "Hepburn" var obj = {name} //amount to var obj = {name:name}
function fn(a,b){ return {a,b}; } var obj = fn("hello","word"); console.log(obj);
Abbreviation of method
In objects, you can abbreviate methods
let obj = { fn(){ console.log("At nine o'clock tonight, the island will gather."); } } //Equal to let obj = { fn:function(){ console.log("At nine o'clock tonight, the island will gather."); } }
Shorthand is only applicable to ordinary methods, and constructors cannot be shorthand.
2... Operator, property name expression
... is an extension operator
The function of splitting. If it is an object, it will traverse all the attributes in the object. If it is an array, it will traverse all the elements
let a = {x:1,y:2} let b = {...a} console.log(b);//{x: 1, y: 2} let arr = [10,20,30]; let c = {...arr} console.log(c["0"]);//10
let obj = { name: "Vivien Leigh", age: "20" } console.log(obj.name); //Vivien Leigh console.log(obj["name"]); //Vivien Leigh
let obj2 = { name: "Vivien Leigh", ["ag" + "e"]: "20" } console.log(obj2); //age: "20" name: "Vivien Leigh"
Case: Dictionary
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="js/demo.js"></script> <style> #box { width: 400px; height: 300px; margin: 100px auto; border: 1px solid; padding: 50px; box-sizing: border-box; background-color: lightblue; } #word { width: 220px; height: 30px; font-size: 18px; } #queryBtn { width: 60px; height: 32px; font-size: 18px; } #desc { width: 290px; height: 160px; background-color: lightgreen; margin-top: 20px; font-size: 18px; } </style> </head> <body> <div id="box"> <input type="text" id="word" placeholder="Please enter the word to query"> <button id="queryBtn">query</button> <div id="desc"></div> </div> <script> var arr = word.split("\n"); // console.log(arr.length); let map = new Map(); for (let i = 0; i < arr.length - 1; i += 2) { let key = arr[i].substring(1); let value = arr[i + 1].substring(6); map.set(key, value); } //Get query button var queryBtn = document.getElementById("queryBtn"); //Get input box var iWord = document.getElementById("word"); // Get div var desc = document.getElementById("desc"); queryBtn.onclick = function() { //Gets the value of the input box. // console.log(iWord.value.trim()); let value = map.get(iWord.value.trim()); if (value) { desc.innerHTML = value; } else { desc.innerHTML = "The word is not found!"; } } </script> </body> </html>