JavaScript -- data type, function, array, string

Posted by jamess on Sun, 16 Jan 2022 13:00:43 +0100

1, Data type

(1) Data type

JavaScript variables can hold a variety of data types: numeric values, string values, arrays, objects, and so on:

var length = 7;                             // number
var lastName = "Gates";                      // character string
var cars = ["Porsche", "Volvo", "BMW"];        // array
var x = {firstName:"Bill", lastName:"Gates"};  // object

(2) JavaScript value

  • JavaScript has only one numeric type.

    You can write values with or without a decimal point:

  • Super large or super small values can be written by scientific counting method:

(3) JavaScript Boolean

Boolean values have only two values: true or false.

(4) JavaScript array

Note: JavaScript arrays are written in square brackets. The items of the array are separated by commas

The array index is based on zero, which means that the first entry is [0], the second entry is [1], and so on.

(5)JavaScript object

JavaScript objects are written in curly braces Object properties are name:value pairs separated by commas.

(6)Undefined and Null

Undefined

In JavaScript, the value of a variable without a value is undefined. typeof also returns undefined.

Null

In JavaScript, null is "nothing". It is seen as something that does not exist.

In JavaScript, the null data type is an object.

  • Null can be understood as an object in JavaScript as a bug. It should have been null.
  • You can empty the object by setting the value to null:
  • You can empty objects by setting the value to undefined:

Difference between Undefined and Null

Undefined and null values are equal, but types are not equal:

(7) Raw data (raw data value is a single simple data value without additional properties and methods.)

The typeof operator returns one of the following primitive types:

  • string
  • number
  • boolean
  • undefined

2, Functions

JavaScript functions are blocks of code designed to perform specific tasks.

JavaScript functions are executed when code calls it.

(1) Function syntax

JavaScript functions are defined by the function keyword, followed by the function name and parentheses ().

Function names can contain letters, numbers, underscores, and dollar signs (the same rules as variable names).
Parentheses can include parameters separated by commas

     function name(Parameter 1, Parameter 2, Parameter 3) {
    Code to execute
}
     

(2) Function call

The code in the function will execute when the function is called by other code:
a key:

  • When an event occurs (when the user clicks the button)
  • When JavaScript code calls
  • Automatic (self calling)

(3) Function return

When JavaScript reaches the return statement, the function stops executing.

If a function is called by a statement, JavaScript will "return" to execute code after the statement is called.

Functions usually calculate the return value. This return value is returned to the caller

Example:

var x = myFunction(7, 8);        // Call the function, and the return value is assigned to x

function myFunction(a, b) {
    return a * b;                // Function returns the product of a and b
}

(4) () operator call function

Using the above example, toCelsius refers to the function object, while toCelsius() refers to the function result

(5) Local variable

Variables declared in JavaScript functions become local variables of functions.

Local variables can only be accessed within functions.

Example:

// carName cannot be used in code here

function myFunction() {
    var carName = "Volvo";
    // code here CAN use carName
}

// The code here can use carName

3, Array

JavaScript arrays are used to store multiple values in a single variable.

  1. array define

An array is a special variable that can hold more than one value at a time

  1. Create an array (two methods)

(1)

var array-name = [item1, item2, ...];

(2) Use JavaScript keyword new

var cars = new Array("Saab", "Volvo", "BMW");
  1. Accessing array elements

Reference the index number (subscript) to refer to an array element

To access the value of the first element in cars:

var name = cars[0];

This statement modifies the first element in cars:

cars[0] = "Opel"
  • Access the first element
fruits = ["Banana", "Orange", "Apple", "Mango"];
var first = fruits[0];
  • Access the last element
fruits = ["Banana", "Orange", "Apple", "Mango"];
var last = fruits[fruits.length - 1];
  1. Arrays are objects

Using the typeof operator on an array in JavaScript will return "object".

(1) Arrays use numbers to access their elements.

In this example, person[0] returns Bill:

var person = ["Bill", "Gates", 62];

(2) Object uses a name to access its members.

In this case, person Firstname returns Bill:

var person = {firstName:"John", lastName:"Doe", age:46};
  1. You can save objects, functions and arrays in the array
myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;
  1. length attribute

The length property returns the length of the array (the number of array elements).

Example:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length;                       // The length of fruits is 4

The length property is always greater than the highest array index (subscript).

  1. Traverse array elements

(1) The safest way to traverse an array is to use a "for" loop:

var fruits, text, fLen, i;

fruits = ["Banana", "Orange", "Apple", "Mango"];
fLen = fruits.length;
text = "<ul>";
for (i = 0; i < fLen; i++) {
     text += "<li>" + fruits[i] + "</li>";
} 
text += "</ul>";

document.getElementById("demo").innerHTML = text;

(2) You can use array Foreach() function:

var fruits, text;
fruits = ["Banana", "Orange", "Apple", "Mango"];

text = "<ul>";
fruits.forEach(myFunction);
text += "</ul>";

document.getElementById("demo").innerHTML = text;

function myFunction(value) {
  text += "<li>" + value + "</li>";
}
  1. Add array element

(1) The best way to add new elements to an array is to use the push() method:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
  fruits.push("Lemon");

(2) To add a new element to the array using the length attribute:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Lemon";  // Add a new element to fruits (Lemon)
  1. Associative array

JavaScript does not support arrays with named indexes.

In JavaScript, arrays can only use numeric indexes.

Warning!
If you use named indexes, JavaScript redefines arrays as standard objects.

After that, all array methods and properties will produce incorrect results.

var x = person.length;         // person.length will return 0
var y = person[0];              // person[0] will return undefined

The difference between arrays and objects

  • In JavaScript, arrays use numeric indexes.
  • In JavaScript, objects use named indexes.

How to recognize arrays?

The problem is that the JavaScript operator typeof returns "object":

(1) Array.isArray():

Array.isArray(fruits);     // Return true

(2) Create your own isArray() function to solve this problem:

function isArray(x) {
    return x.constructor.toString().indexOf("Array") > -1;
}

If the parameter is an array, the above function always returns true.
Or more accurately, if the object prototype contains the word "Array", it returns true.

(3) If the object is created by the given constructor, the instanceof operator returns true:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
 
fruits instanceof Array     // Return true

4, String

JavaScript strings are used to store and manipulate text.

(1) String length
The built-in property length returns the length of the string:

var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;

(2) Special characters

Because the string must be enclosed by quotation marks, JavaScript misunderstands the string:

The solution to avoid this problem is to use the \ escape character.

Backslash escape character converts a special character to a string character:

coderesultdescribe
''Single quotation mark
""Double quotation mark
\\Backslash

(3) Valid escape sequences in the other six JavaScript:

coderesult
\bBackspace key
\fPage change
\nXinxing
\renter
\tHorizontal tab
\vvertical tab
5, String method

(1) Find a string in a string

The indexOf() method returns the index (position) of the first occurrence of the specified text in the string:

example

var str = "The full name of China is the People's Republic of
 China.";
var pos = str.indexOf("China");

(2) JavaScript calculates the position from zero.

0 is the first position in the string, 1 is the second, 2 is the third

The lastIndexOf() method returns the index of the last occurrence of the specified text in the string:

If no text is found, indexOf() and lastIndexOf() both return - 1.

Both methods accept the second parameter as the starting position for retrieval.

var str = "The full name of China is the People's Republic of
 China.";
var pos = str.indexOf("China", 18);
  • The lastIndexOf() method retrieves backward (from end to end), which means that if the second parameter is 50, the retrieval starts from position 50 to the beginning of the string.

(3) Retrieves a string from a string

The search() method searches for a string of a specific value and returns the matching location:

var str = "The full name of China is the People's Republic of 
China.";
var pos = str.search("locate");

The difference is:

  • The search() method cannot set the second start position parameter.
  • The indexOf() method cannot set more powerful search values (regular expressions)

(4) Extract partial string

  • slice(start, end)

    slice() extracts a part of the string and returns the extracted part in the new string.
    This method sets two parameters: start index (start position) and end index (end position).

    var str = "Apple, Banana, Mango";
    var res = str.slice(7,13);
    

    If a parameter is negative, the count starts at the end of the string.

    If the second parameter is omitted, the method will crop the rest of the string

  • substring(start, end)

substring() cannot accept negative indexes.

If the second parameter is omitted, the substring() will crop the rest of the string.

  • substr(start, length)

substr() is similar to slice().

The difference is that the second parameter specifies the length of the extracted part.

var str = "Apple, Banana, Mango";
var res = str.substr(7,6);
  1. If the second parameter is omitted, the substr() will crop the rest of the string.

  2. If the first argument is negative, the position is calculated from the end of the string.

  3. The second parameter cannot be negative because it defines length.

(5) Replace string contents

  • The replace() method replaces the value specified in the string with another value:
str = "Please visit Microsoft!";
var n = str.replace("Microsoft", "W3School");
  • The replace() method does not change the string that calls it. It returns a new string.

By default, replace() replaces only the first match

  • By default, replace() is case sensitive. Therefore, MICROSOFT is not matched:

To perform a case insensitive substitution, use the regular expression / i (case insensitive):

str = "Please visit Microsoft!";
var n = str.replace(/MICROSOFT/i, "W3School");

Note: regular expressions are not quoted.

To replace all matches, use the g flag of the regular expression (for global search):

(6) Convert to uppercase and lowercase

toUpperCase() converts the string to uppercase:

var text1 = "Hello World!";       // character string
var text2 = text1.toUpperCase();  // text2 is text1 converted to uppercase

toLowerCase() converts the string to lowercase:

var text1 = "Hello World!";       // character string
var text2 = text1.toLowerCase();  // text2 is text1 converted to lowercase

(7)concat() method

concat() connects two or more strings:

var text1 = "Hello";
var text2 = "World";
text3 = text1.concat(" ",text2);

The concat() method can be used instead of the addition operator.

All string methods return a new string. They do not modify the original string.

Strings are immutable: strings cannot be changed, only replaced.

(8)String.trim()

The trim() method deletes the whitespace at both ends of the string:

(9) Extract string characters

  • charAt() method

The charAt() method returns the string with the specified subscript (position) in the string:

var str = "HELLO WORLD";
str.charAt(0);            // Return to H
  • charCodeAt() method

The charCodeAt() method returns the character unicode encoding of the specified index in the string:

var str = "HELLO WORLD";

str.charCodeAt(0);         // Return 72

(10) Convert string to array

You can convert strings to arrays through split():

var txt = "a,b,c,d,e";   // character string
txt.split(",");          // Separated by commas
txt.split(" ");          // Separated by spaces
txt.split("|");          // Separated by vertical lines

If the delimiter is omitted, the returned array will contain the entire string in index [0].

If the delimiter is' ', the returned array will be an array separated by a single character:

Topics: Javascript Front-end