JavaScript arrays and string basic operations

Source: Internet
Author: User
Tags add filter empty end string sort split javascript array

JavaScript array Basic operations

An array in JavaScript is a special object that represents the index of an offset as an attribute of the object, which may be an integer, but these numeric indices are internally converted to string types because the property name in the JavaScript object must be a string.

One: How do I create an array?

There are 2 ways to create an array, the first of which is the literal number of objects as follows:

var arrs = []; An empty array was defined.

Another way to do this is to call the constructor of the array to create an array

var arrs = new Array ();

Two: The basic operation of the array is as follows:

1. You can use the Split method to convert a string to an array. are as follows:

Console.log ("AABBCC". Split (""));

Print: ["A", "a", "B", "B", "C", "C"]

2. To convert an array to a string, you can use the Join method . As follows:

Console.log (' AA ', ' BB ', ' VV '].join (""));

Print as follows: AABBVV

3. indexof find elements. used to find out if an element is in an array, and return the index of the array if it exists, otherwise return-1;

["AA", ' BB '].indexof (' BB '); 1

The indexOf () function always returns the index of the first element with the same parameter, and another function similar to that is the LastIndexOf () method, which returns the index of the last element in the same element, or 1 if it is not found.

such as: ["AA", ' BB ', ' cc ', ' AA '].lastindexof (' AA '); 3

["AA", ' BB ', ' cc ', ' AA '].indexof (' AA '); 0

4. Array merging using the Concat () method.

such as: Console.log (["AA", ' BB '].concat ([' CC '])];

return ["AA", "BB", "CC"];

5. The splice () method intercepts a new array from an existing array, the first parameter of which is the initial index of the interception, and the second parameter is the length of the interception. For example, the following code:

["AA", "BBB", "VVV", "ddd", "ee"].splice (2,2)

Return is: ["VVV", "ddd"]

6. The slice () method returns the selected element from an existing array

Arrs.slice (Start,end);

Start must specify where to start the selection, and if it is a negative number, specify the position from the end of the array, for example:-1 is the last element,-2 is the penultimate element.

End optional, which specifies where to close the selection, which is the array subscript at the end of the array fragment, and if not specified, the segmented array contains all the elements from start to the end of the array. For example, as follows:

[' AA ', ' BB ', ' cc ', ' DD '].slice (1,2);

return ["BB"];

7. Push () method, Add the element from the end of the array, such as the following code:

var nums = [1,2,3,4,5];

Nums.push (6);

Console.log (Nums); [1,2,3,4,5,6];

8. The Unshift () method adds one or more elements to the beginning of the array and returns a new length. As follows:

var arrs = [1,2,3,4,5];

Console.log (Arrs.unshift ("AA", "BB")); Return 7

Console.log (ARRS); ["AA", "BB", 1, 2, 3, 4, 5]

9. Pop () method deletes the element at the end of the array. Returns the deleted element

var arrs = [1,2,3,4,5,6];arrs.pop ();

Console.log (Arrs.pop ()); 6

Console.log (ARRS);//1,2,3,4,5

The Shift () method deletes the first element of the array, the following code:

var nums = [9,1,2,3,4,5,6];

Console.log (Nums.shift ()); 9

Console.log (nums);//[1,2,3,4,5,6];

To add and remove elements from the middle of an array, you can use the splice () method to provide the following parameters:

1. Starting index.

2. The number of elements that need to be deleted (the parameter is set to 0 when the element is added);

3. Elements that you want to add into the array.

For example, as follows:

Inserts an element in the middle of an array.

var nums = [1,2,3,7,8,9];

Nums.splice (3,0,4,5,6);

Console.log (nums);//[1,2,3,4,5,6,7,8,9]

Deletes an element from the array.

var nums = [1,2,3,100,200,300,400,4,5];

Nums.splice (3,4);

Console.log (nums);//1,2,3,4,5

11. Array ordering, the first method is: reverse (); This method flips the order of the elements in the array. For example, the following code:

var nums = [1,2,3,4,5];

Nums.reverse ();

Console.log (nums);//5,4,3,2,1

If it is a string sort, you can use the sort () method. The following code:

var arrs = ["Da", "Ade", "CDF", ' BFG '];

Arrs.sort ();

Console.log (ARRS);//["Da", "Ade", "BFG", "CDF"]

But if the array element is a numeric type, there is a problem, such as the following code:

var nums = [3,1,2,100,4,200];

Nums.sort ();

Console.log (nums);//[1, 100, 2, 200, 3, 4]

The sort () method sorts the elements in a dictionary order, so he assumes that the elements are string types. But for the digital type we can simply write a function. For example, the following code:

function Compare (num1,num2) {

return num1–num2;

}

var nums = [3,1,2,100,4,200];

Num.sort (Compare);

Console.log (nums);//1,2,3,4,100,200

Some of the new elements described below are ForEach (), every (), some (), reduce (), reduceright (), map (), filter (). It's done for standard browsers, ie9+,firefox,chrome operations, IE8 and the following are not supported.

One: ForEach () Method: This method takes a function as an argument, and each element of the array uses the function, as follows:

function Square (num) {

Console.log (Num*num);

}

var nums = [1,2,3,4,5,6,7,8,9,10];

Console.log (square) (Nums.foreach);

1,4,9,16,25,36,49,64,81,100

two: Every () method This method takes a function that returns a Boolean type, which is used by each element in the array, true if all returns True, or FALSE, the following code:

function IsEven (arrs) {

return Arrs% 2 = 0;

}

var arrs = [2,4,6,8];

Console.log (Arrs.every (IsEven));

Returns True if the above arrs is [2,4,5,6]; returns false

Three: The Some () method accepts a function that returns a Boolean type, returns True if one is true, and the following code:

function IsEven (arrs) {

return Arrs% 2 = 0;

}

var arrs = [1,5,3,7];

Console.log (Arrs.some (IsEven));

Returns False if the above Arrs = [1,5,3,6]; returns true.

Four: The Reduce () method takes a function that returns a value that starts with an accumulation value and then calls the function on successive elements in the cumulative value and array until the last element in the arrays returns the resulting cumulative value. The following code:

function Add (total,currentval) {

return total + currentval;

}

var nums = [1,2,3,4];

Console.log (Nums.reduce (add));

Returns 10.

JavaScript also provides a Reduceright () method, unlike the reduce () method, which is executed from right to left, and the following demo is an array of strings that manipulate the following code:

function Concat (accumulatedstring,item) {

return accumulatedstring + item;

}

var words = ["AA", ' BB ', ' cc '];

Console.log (Words.reduce (concat));

Return to AABBCC.

But if you use the Reduceright () method, the value starts from the right. The following code:

function Concat (accumulatedstring,item) {

return accumulatedstring + item;

}

var words = ["AA", ' BB ', ' cc '];

Console.log (Words.reduceright (concat));

Print Ccbbaa

Five: The Map () method uses a function for each element in the array to produce new arrays. The following code:

function curve (grade) {

return grade +=5;

}

var grades = [77,78,89,13];

Console.log (Grades.map (curve));//[82,83,94,18]

Here is a string using the map () method to set up the array of demos, as follows:

function A (word) {

return word[0];

}

var words = ["ased", "BVC", "CDE"];

Console.log (Words.map (a)); [' A ', ' B ', ' C '];

Console.log (Words.map ("")); "ABC"

Six: Filter () method: Pass in a function that returns a Boolean type, using the function for all elements in the array, returning a new array, as follows:

function IsEven (num) {

return num% 2 = 0;

}

function isodd (num) {

Return num% 2!= 0;

}

var nums = [];

for (var i = 0; i < i++) {

Nums[i] = i + 1;

}

Console.log (Nums.filter (IsEven)); 2,4,6,8,10

Console.log (Nums.filter (isodd)); 1,3,5,7,9

The following basic methods for summarizing JavaScript strings are as follows:

1. Concat () Method: This method can take multiple parameters to the tail of the specified string. The following code:

var a= "Hello"; var b= "World";

Console.log (A.concat (b)); HelloWorld

2. CharAt (), charCodeAt () method.

CharAt () is used to return the nth character in the string, charcodeat the code to return the nth string in the string. The following code:

var a = "Hello World";

Console.log (A.charat (2)); L

Console.log (A.charcodeat (2))//108

3. IndexOf (), LastIndexOf () method,2 are the location of the lookup string, indexOf () is looking from the beginning, LastIndexOf () is from the tail start, the 2 methods have 2 parameters, The first parameter is the object to find, and the second parameter is the starting position of the lookup. The following code:

var a = "Hello World";

Console.log (A.indexof ("Lo", 1)); 3

Console.log (A.indexof (2)); -1

4. substr (), substring () method.

SUBSTR (start,end); The method intercepts the string based on the specified length, contains 2 parameters, the first parameter is the starting subscript of the intercept string, and the second parameter represents the length of the interception.

The following code:

var a = "Hello World";

Console.log (A.substr (0,5))/Hello

SUBSTRING (start,stop); The position at which the start parameter string begins, and where the stop string ends. The following code:

var a = "Hello World";

Console.log (a.substring (2,5)); Llo

5. Slice () Method:

Slice () is similar to substring (), which intercepts substrings based on the start subscript and end subscript. Slice () method declaration: Slice (start, [end])

The following code:

var a = "Hello World";

Console.log (A.slice (2,5)); Llo

The difference between the slice () method and the substring () method:

Difference 1: If the value of the first parameter is greater than the value of the second parameter, that is, the starting subscript is greater than the end subscript, the substring () method can exchange 2 parameters before the interception is performed, and the Slice () method is invalid, returning an empty string with the following code:

var a = "Hello World";

Console.log (a.substring (11,6)); World

Console.log (A.slice (11,6)); return empty

Difference 2: If the parameter value is negative, the slice () method can interpret the minus sign as starting from the right, the first on the right is-1, the second is-2, and so on. The substring () method is not valid and returns an empty string. The following code:

var a= "Hello World";

Console.log (a.substring ( -5,-1)); Empty

Console.log (A.slice ( -5,-1)); Worl

6. Replace () method

Replace (regexp,replacement); The first parameter represents a regular expression that performs a match, or it can be a string, and the second parameter represents the preparation for a matching substring.

var a = "Hello a";

Console.log (A.replace (/a/g, ' World '))//Hello World

7. toLowerCase (), toUpperCase () method.

toLowerCase () Converts the string to lowercase, touppercase () converts the string to uppercase.

The following code:

var a= "Hello World"

Console.log (A.tolowercase ()); Hello World

Console.log (A.touppercase ()); HELLO World



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.