JS Notes-Array Method [addition, deletion, modification and query]

1. Array operations

Array operations: change of cells in the array, adding cells, deleting cells, modifying cells.

1. [Add] of the array

example:

let obj = [‘张三’,‘李四’,‘王五’]

Specifically, there are two ways to achieve this:

1.1 push()

【结尾处】Adding a new element to an array

Syntax format: array name.push (new unit)

obj.push('赵四');
console.log(obj);// [‘张三’,‘李四’,‘王五’,'赵四']

1.2 unshift()

【开始】add a new element to the array

Syntax format: array name.unshift (new unit)

obj.unshift('哈哈')
console.log(obj);// ['哈哈',‘张三’,‘李四’,‘王五’,'赵四']

1.3 Supplement:

New units can also be added by index value

ArrayName[IndexValue] = NewCell

But it should be noted that the index does not exist in the original array, if it exists, the array unit is modified.

2. [Delete] of the array

example:

let arr = [‘张三’,‘李四’,‘王五’]

Specifically, there are two ways to achieve this:

1.1 pop()

The array can be 【最后一个单元】deleted, and the deleted unit can be obtained.

Syntax format: array name.pop()

let aa = arr.pop();

console.log(aa); // 王五

1.2 shift()

The cells of the array can 【第一个】be deleted, and the deleted cells can be obtained.

Syntax format: array name.shift()

let bb = arr.shift();

console.log(bb); // 张三

Summarize:

After passing popand shiftdeleting the unit, the deleted unit can be obtained.
For example:
let heroes = ['Zhang Fei', 'Zhang Fei 1', 'Zhang Fei 2'];
let aa = heroes.pop(); // 'Zhang Fei 2'

3. Universal modification method splice

When operating on array units, you can use splice to operate on units at [any] position.
It can be added, deleted, or even modified!

Grammar format: array name.splice (subscript, number)

let arr = [‘张三’,‘李四’,‘王五’]

1.1 删除

Grammar format: array name.splice (subscript, number)

arr.splice(1,1);

console.log(arr);// [‘张三’,‘王五’]

For example:
let heroes = ['Zhang Fei', 'Zhang Fei1', 'Zhang Fei2'];
heroes.splice(1,1); // 'Zhang Fei1' is deleted from the array

1.2 Modifications

Grammar format: array name.splice (subscript, number, new unit)

There are as many new units as there are.

// 修改一个
// 数组名.splice(下标,个数,新单元)

arr.splice(0,1,'小张三')

console.log(arr);// ['小张三',‘李四’,‘王五’]

// 修改二个
// 数组名.splice(下标,个数,新单元,新单元)

arr.splice(0,2,'小张三','小李四')

console.log(arr);// ['小张三','小李四',‘王五’]

1.3 add

Syntax format: array name.splice(subscript, 0, new unit)

arr.spilce(0,0,'测试')

console.log(arr);// ['测试',‘张三’,‘李四’,‘王五’]

Guess you like

Origin blog.csdn.net/m0_62181310/article/details/127902323