Common js problems and common js Problems

Source: Internet
Author: User

Common js problems and common js Problems
JavaScript match () method

Definition and usage

The match () method can be used to search for a specified value in a string or to find a match between one or more regular expressions.

This method is similar to indexOf () and lastIndexOf (), but it returns the specified value rather than the position of the string.

Syntax
// Match the string and return the specified value
StringObject. match (searchvalue)
// Matches the Regular Expression and returns the specified value.
StringObject. match (regexp)


Use match () to retrieve a string:
<Html>
<Body>

<Script type = "text/javascript">

Var str = "Hello world! "
Document. write (str. match ("world") + "<br/> ")
Document. write (str. match ("World") + "<br/> ")
Document. write (str. match ("worlld") + "<br/> ")
Document. write (str. match ("world! "))

</Script>

</Body>
</Html>


The final result is, world, null, null, world!


Use match () to retrieve a matching example of a regular expression:
<Html>
<Body>

<Script type = "text/javascript">

Var str = "1 plus 2 equal 3 ";

// G must be added to the regular expression, and global match is required. Otherwise, a value is matched and the return value is returned.
Document. write (str. match (/\ d +/g ))

</Script>

</Body>
</Html>


In general, we use match for many regular expressions. We can also use it to represent indexOf and lastIndexOf to determine whether the value exists in the string.


JavaScript search () method

Definition and usage

The search () method is used to retrieve the specified substring in a string, or to retrieve the substring that matches the regular expression. After retrieval, the start position of the matched substring is returned, the value cannot be retrieved.-1 is returned.

Syntax
StringObject. search (regexp)
// This parameter can be a substring to be retrieved in stringObject or a RegExp object to be retrieved.
// To perform a case-insensitive search, append the flag I.


Search () Example:

<Script type = "text/javascript">

Var str = "Visit W3School! "
Document. write (str. search (/W3School /))

</Script>


The returned index value is 6. search is usually used in combination with regular expressions to achieve the indexOf effect.


JavaScript charAt () method

Definition and usage

The charAt () method returns characters at a specified position.

Note that JavaScript does not have a character data type different from the string type, so the returned character is a string with a length of 1.
Syntax
// Return the string at the specified position
StringObject. charAt (index)


ChartAt instance:
<Script type = "text/javascript">

Var str = "Hello world! "
Document. write (str. charAt (1 ))

</Script>


The final returned result is e. Generally, we can use chartAt to obtain specific characters from a string.


JavaScript charCodeAt () method

Definition and usage

The charCodeAt () method returns the Unicode encoding of characters at the specified position. The returned value is an integer between 0 and 65535.

The charCodeAt () method is similar to the charAt () method, except that the former returns the encoding of the characters at the specified position, and the latter returns the character substrings.

Syntax
StringObject. charCodeAt (index)


CharCodeAt () instance

Note: The subscript of the first character in the string is 0. If the index is a negative number or is greater than or equal to the length of the string, charCodeAt () returns NaN.

<Script type = "text/javascript">

Var str = "Hello world! "
Document. write (str. charCodeAt (1 ))
// Returns the Unicode encoding 101 of H.
</Script>



Array. prototype. map () method in js

Definition and usage

The map () method returns a new array consisting of the returned values after each element in the original array calls a specified method.

Syntax
Array. map (callback [, thisArg])

// The elements in the original callback array return a new element after this method.

// CurrentValue, the first parameter of callback, the element currently passed in the array.

// Index, the second parameter of callback, the index of the currently passed element in the array.

// Array, the third parameter of callback, the array that calls the map method.

// The object this points to when thisArg executes the callback function.


The map method calls the callback function once in order for each element in the original array. The returned values after each callback operation are combined to form a new array. The callback function will only be called with a value index; those that have never been assigned or used

The deleted index is not called. The callback function is automatically passed in three parameters: array elements, element indexes, and the original array.

The first example of using map:

The following code converts all words in an array into the corresponding plural form.

Function fuzzyPlural (single ){
Var result = single. replace (/o/g, 'E ');
If (single = 'hangaroo '){
Result + = 'se ';
}
Return result;
}

Var words = ["foot", "goose", "moose", "kangaroo"];
Console. log (words. map (fuzzyPlural ));

// The final result ["feet", "geese", "meese", "kangareese"]


Run the code copy code Save the code prompt: you can modify some code before running! Power by W3Cfuns.com


Example of finding the square root of each element in an array

Var numbers = [1, 4, 9];
Var roots = numbers. map (Math. sqrt );
/* The value of roots is [1, 2, 3], and the value of numbers is still [1, 4, 9] */


Use the map method on the string
Var map = Array. prototype. map
Var a = map. call ("Hello World", function (x) {return x. charCodeAt (0 );})
// The value of a is [72,101,108,108,111, 32, 87,111,114,108,100]


<! Doctype html>
<Html lang = "en-US">
<Head>
<Meta charset = "UTF-8">
<Title> </title>
</Head>
<Body>
<Script type = "text/javascript">
// Var map = Array. prototype. map
Var a = Array. prototype. map. call ("Hello World", function (x) {return x. charCodeAt (0 );})
// The value of a is [72,101,108,108,111, 32, 87,111,114,108,100]
Alert ();
</Script>
</Body>
</Html>


Map is compatible with the old environment

Map is a newly added method in the recent ECMA-262 standard; so some older browsers may not implement this method. In browsers that do not have native support for the map method, you can use the following Javascript code to implement it. The
The algorithm is exactly what ECMA-262, version 5th stipulates. Assume that the Object, TypeError, and Array have their original values. The original value of callback. call is also Function. prototype. call.
// Implement ECMA-262, Edition 5, 15.4.4.19
// Reference: http://es5.github.com/#x15.4.4.19
If (! Array. prototype. map ){
Array. prototype. map = function (callback, thisArg ){

Var T, A, k;

If (this = null ){
Throw new TypeError ("this is null or not defined ");
}

// 1. Assign O to the array that calls the map method.
Var O = Object (this );

// 2. Assign len to the length of array O.
Var len = O. length >>> 0;

// 4. If callback is not a function, a TypeError exception is thrown.
If ({}. toString. call (callback )! = "[Object Function]") {
Throw new TypeError (callback + "is not a function ");
}

// 5. If the thisArg parameter has a value, assign T to thisArg; otherwise, T is undefined.
If (thisArg ){
T = thisArg;
}

// 6. Create A new array with the length of len
A = new Array (len );

// 7. Assign k to 0
K = 0;

// 8. When k <len, the loop is executed.
While (k <len ){

Var kValue, mappedValue;

// Traverse O, and k is the original array index
If (k in O ){

// KValue is the value corresponding to index k.
KValue = O [k];

// Execute callback. this points to T. The parameters include kValue, k: Index, and O: original array.
MappedValue = callback. call (T, kValue, k, O );

// Add the returned values to group.
A [k] = mappedValue;
}
// K auto-increment 1
K ++;
}

// 9. Return the new array
Return;
};
}



Method In javascript: Array. prototype. slice. call (arguments)

There is also a common knowledge point, which we usually see in the past. prototype. slice. call (arguments, 1) or Array. prototype. slice. call (arguments) is a bit confusing. In fact, we use Array. prototype

Slice () converts arguments into an array, which makes it easier to use.

Example

<Script type = "text/javascript">
Var B = Array. prototype. slice. call ("HelloWorld ");
Console. log (B );
</Script>


The output result is array ['h', 'E', 'l', 'l', 'O', 'w', 'O', 'R ', 'l', 'D']


Comparison between Array. prototype. map. call (obj, charFun) and Array. prototype. slice. call (obj). map (charFun)

<Script type = "text/javascript">
// Var map = Array. prototype. map
Var a = Array. prototype. map. call ("Hello World", function (x) {return x. charCodeAt (0 );})
// The value of a is [72,101,108,108,111, 32, 87,111,114,108,100]
Alert ();

Function char (x) {return x. charCodeAt (0 );}
Var B = Array. prototype. slice. call ("HelloWorld"). map (char );
Console. log (B );
</Script>


The output result is [72,101,108,108,111, 32, 87,111,114,108,100], Array. prototype. map. call (obj, charFun) and Array. prototype. slice. call (obj ). map (charFun) achieves the same effect and converts all strings into new arrays.
Who said a few good js material networks?

Lazy website js.alixixi.com aixixi www.lanw.uku.com lazy library is very good

Then, how do you implement JS?

Js can achieve asynchronous operations and you can check the Internet
You can copy the following to a text file, preferably in UTF-8 format.
Some punctuation marks may be filtered out after I change the punctuation marks.
This is the simplest example.

<Span id = "a" onclick = "a ()"> click me to refresh </span>
<P> I won't be refreshed.
<Script>
Function a () {document. getElementById ("a"). innerHTML = "I have been refreshed ";}
</Script>
==========================================
You can't do this. The main thing is, do you want to check the rest?
Although it is a good habit to ask questions, you must have a certain degree of self-learning ability.
Baidu searches for functions with scheduled execution

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.