JavaScript function, i.e., string objects

JavaScript function

JavaScript function defined by the function keyword, followed by the function name and the brackets ().
Function name can contain letters, numbers, underscores and dollar sign (same rules and variable names).
Parentheses may include parameters separated by commas

function name(参数 1, 参数 2, 参数 3) {
    要执行的代码
}

Perform a function in the code calls the function in the other code:

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


Examples
to convert Fahrenheit to Celsius:

function toCelsius(fahrenheit) {
    return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius(77);

Using the above example, toCelsius reference the function object, and toCelsius () is a function of the results quoted

function toCelsius(fahrenheit) {
    return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius;    //结果为function toCelsius(f) { return (5/9) * (f-32); }

Variables declared in a JavaScript function, will be a function of local variables .
Local variables can only be accessed within the function.


JavaScript objects

Examples

var person = {
  firstName: "Bill",
  lastName : "Gates",
  id       : 678,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};


Access object properties

person.id

or

person["id"]


Object Access Method

name = person.fullName();

If you do not use () to access fullName method will return the function definition :

name = person.fullName;    //function() { return this.firstName + " " + this.lastName; }


JavaScript events


Typically, when an event occurs, the user will want to do something.
JavaScript allows you to execute code when an event is detected.
Through JavaScript code , HTML allows you to add event handlers to HTML elements.
In the following example, onclick attribute (and code) is added to the button elements:

<button onclick='document.getElementById("demo").innerHTML=Date()'>现在的时间是?</button>

In the following example, the code (using this.innerHTML) changes its own content elements:

<button onclick="this.innerHTML=Date()">现在的时间是?</button>


Here are some common HTML event

event description
onchange HTML element has been changed
onclick The user clicks on an HTML element
onmouseover Move the mouse to a user HTML element
onMouseOut The user mouses HTML elements
onkeydown User presses a key
onload The browser has finished loading the page


JavaScript string

JavaScript strings are enclosed in quotation marks zero or more characters.
You can use quotation marks in strings, it does not match the quotation marks around the string can be:

var answer = "It's good to see you again!";
var answer = "He is called 'Bill'";
var answer = 'He is called "Bill"';

Built property length returns the string length :

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


Escape character

Code result description
' ' apostrophe
" " Double quotes
\ \ Backslash

JavaScript six other valid escape sequences:

Code result
\b Backspace
\f Feed
\n New row
\r Enter
\t Horizontal tab
\ v Vertical tab


Wrap the long code
can change so

document.getElementById("demo").innerHTML =
"Hello Kitty.";

You may also change in the string

document.getElementById("demo").innerHTML = "Hello \
Kitty";

 The method is not the ECMAScript (JavaScript) standard.
Some browsers do not allow space after the character.
The safest approach to wrap a long string of (but a bit slow) is using strings addition:

document.getElementById("demo").innerHTML = "Hello " + 
"Kitty!";

You can not be a backslash wrap lines of code:

document.getElementById("demo").innerHTML = \ 
"Hello Kitty!";    //这是错误的,不会被执行


The string can also be a target (but not recommended, as this will slow down the speed)

var firstName = new String("Bill")
var x = "Bill";
var y = new String("Bill");
// typeof x 将返回 string
// typeof y 将返回 object

When using == equality operators, equal strings are equal

var x = "Bill";             
var y = new String("Bill");
// (x == y) 为 true,因为 x 和 y 的值相等

When using === operator, the strings are equal are not equal, since the operator needs === simultaneously equal type and value.

var x = "Bill";             
var y = new String("Bill");
//(x === y) 为 false,因为 x 和 y 的类型不同(字符串与对象)

Or worse. Objects can not be compared

var x = new String("Bill");             
var y = new String("Bill");
// (x == y) 为 false,因为 x 和 y 是不同的对象
// (x === y) 为 false,因为 x 和 y 是不同的对象

JavaScript object can not be compared to compare two objects JavaScript will always return false.


String Methods

Length of the string
length property returns the length of the string

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


Find substring

indexOf () method returns the string specified in the text for the first time the index appears (position)

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

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

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

If the text is not found, the indexOf () and lastIndexOf () returns -1 are
two ways to accept the second parameter as a search starting position
lastIndexOf () methods to retrieve (backward head from the tail ), which means: if the second parameter is 50, from position 50 to start searching until the start of the string. Note that the final result is given from the beginning to end of the string index position


Retrieving substring

search () method of the search string specified value, and returns the position matching

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

Both methods, the indexOf () and Search (), are both equal, there are different .
The difference is that:

  • search () method can not set the start position of the second parameter.
  • indexOf () method can not be set more powerful search value (regular expressions).


Extract strings

slice () extracts a certain portion of the string and the return portion is extracted in a new string. The method set two parameters: starting index (starting position), a stop index (end position).

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

If a parameter is negative, counting from the end of the string.
In this example the string position of the cropped slice position -13 to -8

var str = "Apple, Banana, Mango";
var res = str.slice(-13,-7);  //包含-13,-6截至,不包含-7 ,Banana

If omitted, the remaining portion of the second argument, the method of the crop string

var res = str.slice(7);  //Banana, Mango

substring () is similar to slice ().
The difference is that substring () can not accept the negative index.

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

substr () is similar to slice ().
Except that the portion of the second parameter is extracted predetermined length .

var str = "Apple, Banana, Mango";
var res = str.substr(7,7);  //Banana,

If the second parameter is omitted, the substr () the remainder of the crop string.

var str = "Apple, Banana, Mango";
var res = str.substr(7);  //Banana, Mango

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

var str = "Apple, Banana, Mango";
var res = str.substr(-5);  //Mango

The second parameter can not be negative, as it is defined length.


SUMMARY replacement string
replace () method replaces the value specified in string with another value:

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

By default, replace () replaces only the first match
by default, replace () is case sensitive.

For case-insensitive replacement is performed, use a regular expression / i (case insensitive)

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

To replace all occurrences, use a regular expression symbol g (for global search)

str = "Please visit Microsoft and Microsoft!";
var n = str.replace(/Microsoft/g, "W3School");
// 请访问 W3School 和 W3School!


Change case
by toUpperCase () to convert a string to upper case

var text1 = "Hello World!";       // 字符串
var text2 = text1.toUpperCase();  // text2 是被转换为大写的 text1,即HELLO WORLD!

By the toLowerCase () to convert strings to lower

var text1 = "Hello World!";       // 字符串
var text2 = text1.toLowerCase();  // text2 是被转换为小写的 text1,即hello world

concat () method can be used instead of the addition operator. The following two lines are equivalent

var text = "Hello" + " " + "World!";
var text = "Hello".concat(" ","World!");

All string method will return a new string. They do not modify the original string
official said: strings are immutable: the string can not be changed, only replace

trim () method removes both ends of the string whitespace

var str = "       Hello World!        ";
alert(str.trim());  //Hello World!

Warning: Internet Explorer 8 or earlier does not support trim () method. For support IE 8, with that you can use regular expressions replace () method instead of

var str = "       Hello World!        ";
alert(str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''));

You can also use the above program to replace the trim function to add JavaScript String.prototype

if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
var str = "       Hello World!        ";
alert(str.trim());


Extract a string of characters

These are two of the strings of characters safety methods:

  • charAt(position)
  • charCodeAt(position)

the charAt () method returns the string in the specified index (position) of the string

var str = "HELLO WORLD";
str.charAt(0);            // 返回 H

the charCodeAt () method returns the string of unicode character coding specified index

var str = "HELLO WORLD";
str.charCodeAt(0);         // 返回 72


Property access

var str = "HELLO WORLD";
str[0];                   // 返回 H

Property access is not too tricky:

  • NA 7 or earlier versions of Internet Explorer
  • It makes an array of strings looks like (not really)
  • If you can not find the character, [] returns undefined, but charAt () returns an empty string.
  • It is read-only. str [0] = "A" is not an error (but it will not work!) strings are immutable


String into an array
can be split () to convert a string array

var txt = "a,b,c,d,e";      // 字符串
txt.split(",");           // 用逗号分隔
txt.split(" ");           // 用空格分隔
txt.split("|");           // 用竖线分隔

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

var str = "a,b,c,d,e,f";
var arr = str.split();
document.getElementById("demo").innerHTML = arr[0];  //a[0]="a,b,c,d,e,f"

If the separator is ".", Will be returned array is an array of character spacing single

var txt = "Hello";       // 字符串
var arr = txt.split("");   // 分隔为字符arr[0]=H

Guess you like

Origin www.cnblogs.com/leerep/p/12318890.html