Home > Web Front-end > JS Tutorial > Parsing of Array arrays in javascript (with examples)

Parsing of Array arrays in javascript (with examples)

不言
Release: 2018-08-31 11:22:28
Original
1551 people have browsed it

The content of this article is about the analysis of Array arrays in JavaScript (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Array object

Syntax for creating Array objects

new Array();
new Array(size);
new Array(element0, element1, ..., elementn);
Copy after login

Parameters

Parameter size is the expected number of array elements. In the returned array, the length field will be set to the value of size.

Parameter element ..., elementn is the parameter list. When the constructor Array() is called with these arguments, the elements of the newly created array are initialized to these values. Its length field will also be set to the number of parameters.

Return value

Returns the newly created and initialized array.

If no parameters are used when calling the constructor Array(), the returned array will be empty and the length field will be 0.

When you call the constructor and only pass it a numeric parameter, the constructor will return an array with the specified number of elements and undefined.

When Array() is called with other parameters, the constructor will initialize the array with the value specified by the parameter.

When the constructor is called as a function without using the new operator, it behaves exactly the same as when it is called with the new operator.

Array Object Properties

constructor Returns a reference to the array function that created this object.
length Set or return the number of elements in the array.
prototype gives you the ability to add properties and methods to objects.

Array Object Method

Method               Description
concat()  Concatenates two or more arrays and returns the result.
join() Put all elements of the array into a string. Elements are separated by the specified delimiter.
pop() Removes and returns the last element of the array
push() Adds one or more elements to the end of the array and returns the new length.
reverse() Reverse the order of elements in the array.
shift() Deletes and returns the first element of the array
slice() Returns the selected element from an existing array
sort() Sorts the elements of the array
splice( ) removes elements and adds new elements to the array.
toSource() Returns the source code of the object.
toString() Convert the array to a string and return the result.
toLocaleString() Convert the array to a local array and return the result.
unshift() Adds one or more elements to the beginning of the array and returns the new length.
valueOf() Returns the original value of the array object

Example

1. Use join(" ") to format the output

Use join to format the output: each Elements are separated by spaces

let b = new Array();
....
//格式化输出
//let str = "";
//for(let i = 0; i < n-1; i++){
    //str+=b[i];
    //str+=" ";
//}
//str+=b[n-1];
//print(str);

//使用join格式化输出

let ans = b.join(" ");
print(ans);
Copy after login

2. Array circular shift to the right

Array circular shift to the right: arr.unshift(arr.pop())

function RoundShift(arr , count) {
    for (var i = 0; i< count; i++) {
        arr.unshift(arr.pop());
        //unshift()    向数组的开头添加一个或更多元素,并返回新的长度
        //pop()    删除并返回数组的最后一个元素
        //shift()    删除并返回数组的第一个元素
        //push()    向数组的末尾添加一个或更多元素,并返回新的长度
    }
}
var arr = [1,2,3,4,5,6,7];
RoundShift(arr, 3);
console.log(arr);
Copy after login

String circular shift to the right :str.substring(start, stop)

function shiftLeft(str, n) {
    var len = str.length;
    // 因为是循环移动,所以需要处理移动位数大于字符串长度的情况
    n = n % len;
    return str.substring(n, len) + str.substring(0, n);
}
var s= shiftLeft('abcdefg', 2);
console.log(s); // "cdefgab"
s = shiftLeft('abcdefg', 10);
console.log(s); // "defgabc"
Copy after login

Compare two strings to see if they are cyclic words: substring(start, stop)

function shiftLeft(str1, str2){
    if(str1.length!=str2.length){return false;}
    for(let i = 0; i < str1.length; i++){
        let s = str1.substring(i) + str1.substring(0,i);
        if(s==str2){
            return true;
        }
    } 
    return false;
}
Copy after login

3. Sort sort()

Custom sorting comparison function

let lines = readline().split(" ");
let arr = new Array(n);
for(let i = 0; i < lines.length; i++){
    arr[i] = parseInt(lines[i]);
}
arr.sort(cmp);
print(arr);
//比较函数,保证正确排序
function cmp(x,y){
    return x-y;
}
Copy after login

4.slice() and splice()

slice()

Definition and usage

# The ##slice() method returns selected elements from an existing array.


Syntax

arrayObject.slice(start,end)
Copy after login
Parameter Description

start Required. Specifies where to start the selection. If negative, it specifies the position from the end of the array. That is, -1 refers to the last element, -2 refers to the second to last element, and so on.

end Optional. Specifies where the selection ends. This parameter is the array index at the end of the array fragment. If this parameter is not specified, the split array contains all elements from start to the end of the array. If this parameter is negative, it specifies the elements starting from the end of the array.

Return value

Returns a new array containing the elements in arrayObject from start to end (excluding this element).


Explanation

Please note that this method does not modify the array, but returns a subarray. If you want to delete a segment of elements from an array, you should use the method Array.splice().


Tips and Notes

Note: You can use negative values ​​to select elements from the tail of an array.


Note:

If end is not specified, the slice() method will select all elements from start to the end of the array.


splice()

Definition and usage

splice() method adds/removes items to/from the array and returns the Deleted items.


Note: This method will change the original array.

Syntax

arrayObject.splice(index,howmany,item1,.....,itemX)
Copy after login
Parameter Description

index Required. An integer specifying the position at which to add/remove an item. Use a negative number to specify the position from the end of the array.

howmany Required. The number of items to delete. If set to 0, items will not be deleted.
item1, ..., itemX Optional. New items added to the array.

Return value

Type Description

Array A new array containing the deleted items, if any.

illustrate

The splice() method removes zero or more elements starting at index and replaces those removed elements with one or more values ​​declared in the parameter list.

If an element is deleted from arrayObject, an array containing the deleted element is returned.

Related recommendations:

Extension function examples of Array array objects in JavaScript programs

Instructions for using Array objects in JavaScript _javascript skills

The above is the detailed content of Parsing of Array arrays in javascript (with examples). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template