JS array splice() function and test script

JS array splice() function and test script

Features

The splice() method adds elements to the array or deletes elements from the array, and then returns the processed array.

Array.splice(index,howmany,item1,…,itemX)

The parameter description
index is required. Integer, specifies the position of adding/deleting items, using negative numbers can specify the position from the end of the array.
howmany required. The number of items to delete. If set to 0, the item will not be deleted.
item1, …, itemX is optional. New items added to the array.

Test script

The content of the test script test.js is as follows:

// JavaScript Document
var db = new Array();
db[0] = {
    
    "x1": "1"};
db[1] = {
    
    "y1": "2"};

console.log(db[0]);
console.log(db[1]);

//to add two elements
db.splice(2,0,{
    
    "x2":"2"},{
    
    "y2":"4"});

console.log(db[2]);
console.log(db[3]);    

//to change 1 element
db.splice(3,1,{
    
    "y2":"6"});
console.log(db[3]);

//to delete 1 element
db.splice(3,1);
console.log(db.length);

var record = {
    
    "t20180906001":{
    
    "data1":"9"}}
db.splice(3,0,record);
console.log(db[3]);

var oneelement = db[3];
console.log(oneelement.t20180906001);
console.log(oneelement.t20180906001.data1);

//written by Pegasus Yu 2018-09-06

The above script embodies the function of adding, modifying and deleting components using the slice() function.
In the Node.js console environment, execute node test to see:
Insert picture description here

-End-

Guess you like

Origin blog.csdn.net/hwytree/article/details/103334711