Examples of JavaScript array operations and object manipulation skills

Table of contents

javascript array manipulation

for loop

for in loop

for loop

forEach loop

map traversal

filter operation

concat operation

sortsort

some other operations

object manipulation

Java enumeration (enum)

example

Using enums in inner classes

example

iterate over enumeration elements

example

Use enum class in switch

example

values(), ordinal() and valueOf() methods

example

enum class members

example

Summarize


javascript array manipulation

Today, I javascriptwill explain some common operations of arrays, hoping to be helpful to developers. Let's look at the three common loops below.

for loop

var arr =[1, 3, 8, 4]
for (var i = 0,j = arr.length; i < j; i++) {
    console.log(arr[i], i)
}
// Prints:
// [0] is 1 0
// [1] is 3 1
// [2] is 8 2
// [3] is 4 3
for in loop

var arr =[1, 3, 8, 4]
var map ={a: 1,b: 2,c: 3}
Array.prototype.text =5
for (var i in arr) {
    console.log(arr[i], i)
}

for (var i in map) {
   console.log(map[i], i)
}
// Prints arr:
// [0] is 1 "0"
// [1] is 3 "1"
// [2] is 8 "2"
// [3] is 4 "3"
// [4] is 5 "text"

//prints map:
// [0] is 1 "a"
// [1] is 2 "b"
// [2] is 3 "c"

for loop

var arr =[1, 3, 8, 4]
for (var i of arr) {
    console.log(i)
}
// Prints:
// [0] is 1
// [1] is 2
// [2] is 3
// [3] is 8
// [4] is 4

It can be seen that forthe loop and for ofthe loop both traverse the array itself, but the difference is the value of i, the former is the index, and the latter is the array value. for inThe loop not only traverses the array itself, but also traverses the prototype, and can traverse objects at the same time. Note here that the value of i is stringof the type "0,1,2,3" Summary: forthe loop can satisfy most of our situations, but it is the most troublesome, getting the index, it is better to for ofget the array directly like that value. for inThe loop function is the strongest and can traverse objects, but the shortcoming is to traverse the prototype object, which may sometimes affect our traversal. The above 3 loops can breakpass out of the loop.

forEach loop

var arr =[1, 3, 8, 4]
arr.forEach((row, index, test) = >{
    console.log(row, index, test)
})
// Prints:
// [0] is 1 0 arr
// [1] is 2 1 arr
// [2] is 3 2 arr
// [3] is 8 3 arr
// [4] is 4 4 arr

It can be seen that forEachthe loop and for inthe loop are very similar, the difference is forEachthat the traversal is in the form of a callback function, and the parameters are the array value, index and the array itself. During the traversal, the rowarray itself can be processed and the array itself will be changed. forEachIt is not so friendly to the need to interrupt the traversal, and breakthe loop cannot be ended by passing. In most cases forEach, it is easy to satisfy our traversal, but forEachthe loop has the problem of context variables (if the arrow function cannot be used, the arrow function is used to avoid this problem).

map traversal

var arr =[1, 3, 8, 4]
var newArr = arr.map((row, index, test) = >{
    return row
})
arr.push(5)
console.log(arr, newArr)
// Prints:
//[1,3,8,4,5],[1,3,8,4]

mapThe traversal forEachis the same as the traversal parameter. The callback function is also used to traverse the entire array. The difference is that mapthe traversal returnreturns us a brand new array.

filter operation

var arr =[1, 3, 8, 4]
var newArr = arr.filter((row, index, test) = >{
    return row >= 5
})
console.log(newArr)
// Prints:
//[8]

filterThe operation is used to filter the array, find the value that meets the condition and return a new array, the parameters of the callback function are the same forEach, and return true falseto determine whether the condition of the new array is met.

concat operation

var arr =[1, 3, 8, 4]
var arr2 =[4, 5]
var newArr = arr.concat(arr2)
var newArr1 = arr.concat()
console.log(newArr, arr2)
// Prints:
//[1, 3, 8, 4, 4, 5]
//[1, 3, 8, 4]

concatOperations are used to combine arrays and return a new array. There is a show operation here that arr.concat()can easily copy an array with only one line of code.

sortsort

var arr =[1, 3, 8, 4]
arr.sort((a, b) = >a > b)
console.log(arr)
// Prints:
// [1, 3, 4, 8]

sort sorts the array and accepts a callback function. The parameter of the function is 2 consecutive items in the array. The above code similarly implements a bubble sort, and returns true falseto

some other operations

//shift:删除原数组第一项,并返回删除元素的值;如果数组为空则返回undefined
//unshift:将参数添加到原数组开头,并返回数组的长度
//pop:删除原数组最后一项,并返回删除元素的值;如果数组为空则返回undefined
//push:将参数添加到原数组末尾,并返回数组的长度
//reverse:将数组反序
//splice(start,deleteCount,val1,val2,...):从start位置开始删除deleteCount项,并从该位置起插入val1,val2,...
//slice(start,end):返回从原数组中指定开始下标到结束下标之间的项组成的新数组
//join(separator):将数组的元素组起一个字符串,以separator为分隔符,省略的话则用默认用逗号为分隔符
//some(),every()判断数组中是否存在满足条件的值,前者有一个为true则返回true,后者所有未true才返回true,有点像&&和||。

//这里写一个数组比较的问题
[]==[]
//prints:false
var a1 =[1, 2, 3]
var a2 =[1, 2, 3]
a1.toString() == a2.toString()
//prints:true
//上面的方式巧妙的避开了大量代码来判断数组是否相同
object manipulation

var map1 ={name: 'jack',age: 21,sex: '0'}
var map2 ={phone: '123456'}
var map3 =Object.assign(map1, map2)
var arr =Object.keys(map1)
console.log(arr)
console.log(map3)
//prints:
//["name", "age", "sex"]
//{name: "jack", age: 21, sex: "0", phone: "123456"}

You can see that Object.keysthe method can keyform an array of objects, and when we get the array, we can use forEachsome other methods to traverse the object. Object.assignThe properties of n objects can be merged, and the latter properties will overwrite the previous properties, and finally a new object will be obtained. These two es6 methods are very practical.

Java enumeration (enum)

A Java enumeration is a special class that generally represents a set of constants, such as 4 seasons in a year, 12 months in a year, 7 days in a week, and directions such as east, west, north, and so on.

A Java enumeration class is defined using the enum keyword, and each constant is separated by a comma, .

For example, define a color enumeration class.

enum Color 
{ 
    RED, GREEN, BLUE; 
} 

The color constants of the above enumerated class Color include RED, GREEN, BLUE, which represent red, green, and blue respectively.

Example of use:

example

enum Color
{
RED, GREEN, BLUE;
}

public class Test
{ // Execution output public static void main(String[] args) { Color c1 = Color.RED; System.out.println(c1); } }






The output of executing the above code is:

RED

Using enums in inner classes

Enumeration classes can also be declared in inner classes:

example

public class Test
{
enum Color
{
RED, GREEN, BLUE;
}

// Execution output
public static void main(String[] args)
{ Color c1 = Color.RED; System.out.println(c1); } }



The output of executing the above code is:

RED

Each enumeration is implemented internally through Class, and all enumeration values ​​are public static final.

The above enumeration class Color conversion is implemented in the inner class:

class Color
{
     public static final Color RED = new Color();
     public static final Color BLUE = new Color();
     public static final Color GREEN = new Color();
}

iterate over enumeration elements

The elements of an enumeration can be iterated using the for statement:

example

enum Color
{
RED, GREEN, BLUE;
}
public class MyClass {
public static void main(String[] args) {
for (Color myVar : Color.values()) {
System.out.println(myVar);
}
}
}

The output of executing the above code is:

RED
GREEN
BLUE

Use enum class in switch

Enumeration classes are often used in switch statements:

example

enum Color
{
RED, GREEN, BLUE;
}
public class MyClass {
public static void main(String[] args) {
Color myVar = Color.BLUE;

switch(myVar) { case RED: System.out.println("Red"); break; case GREEN: System.out.println("Green"); break; case BLUE: System.out.println("Blue" ); break; } } }











The output of executing the above code is:

蓝色

values(), ordinal() and valueOf() methods

The enumeration class defined by enum inherits the java.lang.Enum class by default and implements the java.lang.Serializable and java.lang.Comparable interfaces.

The values(), ordinal() and valueOf() methods are located in the java.lang.Enum class:

  • values() returns all the values ​​in the enumeration class.
  • The ordinal() method finds the index of each enumeration constant, just like an array index.
  • The valueOf() method returns the enumeration constant for the specified string value.

example

enum Color
{
RED, GREEN, BLUE;
}

public class Test
{
public static void main(String[] args)
{
// 调用 values()
Color[] arr = Color.values();

// iterate enumeration
for (Color col : arr)
{ // view index System.out.println(col + " at index " + col.ordinal()); }


// Use valueOf() to return the enumeration constant, if it does not exist, an IllegalArgumentException will be reported
System.out.println(Color.valueOf("RED"));
// System.out.println(Color.valueOf("WHITE")) ;
}
}

The output of executing the above code is:

RED at index 0
GREEN at index 1
BLUE at index 2
RED

enum class members

Enumerations can use their own variables, methods, and constructors just like ordinary classes. Constructors can only use private access modifiers, so they cannot be called externally.

Enumerations can contain both concrete and abstract methods. If an enum class has an abstract method, every instance of the enum class must implement it.

example

enum Color
{
RED, GREEN, BLUE;

// Constructor
private Color()
{ System.out.println("Constructor called for : " + this.toString()); }

public void colorInfo()
{
System.out.println("Universal Color");
}
}

public class Test
{
// 输出
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
c1.colorInfo();
}
}

The output of executing the above code is:


Constructor called for : RED
Constructor called for : GREEN
Constructor called for : BLUE
RED
Universal Color

Summarize

Arrays are a common array type in javascript, and there are many operations. Choosing an appropriate method can improve program performance and code readability. Some functions are only available in es6 and will not be explained here, and the specific operation performance will not be compared.


 

Guess you like

Origin blog.csdn.net/qq_48652579/article/details/131407430