Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities
Conversion method
All objects have toLocaleString(), toString(), and valueOf() methods, and valueOf() returns the array itself. ToString () returns a comma-separated string concatenated with the equivalent strings of each value in the array. Each value of the array is called its toString() method.
let study = ["web"."java"."php"]; // Create an array of three strings
console.log(study.toString()); // web,java,php
console.log(study.valueOf()); // web,java,php
console.log(study); // web,java,php
Copy the code
The toLocaleString() method may also return the same result as toString() and valueOf(), for example
let num1 = {
toLocaleString() {
return "1";
},
toString() {
return "2"; }};let num2 = {
toLocaleString() {
return "3";
},
toString() {
return "4"; }};let num = [num1, num2];
console.log(num); / / 2, 4
console.log(num.toString()); / / 2, 4
console.log(num.toLocaleString()); / / 1 to 3
Copy the code
Two objects are defined, and both the toString and toLocaleString methods are defined, with different return values. We defined num to receive two values, and found that the two methods were called to get different values.
Note: If an item in the array is null or undefined, it is represented as an empty string in the result returned by JOIN (), toLocaleString(), toString(), and valueOf().
The stack method
The stack is a LIFO (last-in-first-out) structure, In which the most recently added item is deleted First. Insertion of data items (called push, push) and deletion (called pop, pop). You can use push() and pop() methods in arrays.
let num = nums.push("1"."2"); // Push two terms
console.log(num); / / 2
count = nums.push("3"); // Push one more term
console.log(num); / / 3
let item = nums.pop(); // Get the last item
console.log(item); / / 3
console.log(colors.length); / / 2
Copy the code
Queue method
Queues restrict access on a first-in, first-out (FIFO) basis. Queues add data at the end of the list, but get data from the beginning of the list. You can use shift() and push() in arrays.
let nums = new Array(a);// Create an array
let num = nums.push("1"."2"); // Push two terms
console.log(num); / / 2
num = nums.push("3"); // Push one more term
console.log(num); / / 3
let item = nums.shift(); // get the first item
console.log(item); / / 1
console.log(nums.length); / / 2
Copy the code
ECMAScript also provides the unshift() method for arrays. As the name implies, unshift() does the opposite of shift().