Home Web Front-end JS Tutorial JavaScript common definitions and methods

JavaScript common definitions and methods

Jun 26, 2017 pm 03:02 PM
javascript js Commonly used method

1. Some common string methods. Note that calling these methods will not change the content of the original string, but will return a new string.
toUpperCase()
Change a string to all uppercase:

var s = 'Hello';
s.toUpperCase(); // 返回'HELLO'
Copy after login


toLowerCase()
Change a string to all lowercase:

var s = 'Hello';var lower = s.toLowerCase(); // 返回'hello'并赋值给变量lowerlower; // 'hello'
Copy after login


indexOf()
will search for the occurrence of the specified string:

var s = 'hello, world';
s.indexOf('world'); // 返回7s.indexOf('World'); // 没有找到指定的子串,返回-1
Copy after login


substring()
Return the substring of the specified index interval:

var s = 'hello, world's.substring(0, 5); // 从索引0开始到5(不包括5),返回'hello's.substring(7); // 从索引7开始到结束,返回'world'
Copy after login


2. Common array methods
indexOf()
To search for the position of a specified element

var arr = [10, 20, '30', 'xyz'];
arr.indexOf(10); // 元素10的索引为0arr.indexOf(20); // 元素20的索引为1arr.indexOf(30); // 元素30没有找到,返回-1arr.indexOf('30'); // 元素'30'的索引为2
Copy after login


slice()
Intercept some elements of Array, and then return a new Array:

var arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
arr.slice(0, 3); // 从索引0开始,到索引3结束,但不包括索引3: ['A', 'B', 'C']arr.slice(3); // 从索引3开始到结束: ['D', 'E', 'F', 'G']
Copy after login

Note that slice( )'s start and end parameters include the start index and do not include the end index.
If you do not pass any parameters to slice(), it will intercept all elements from beginning to end. Taking advantage of this, we can easily copy an Array.

push and pop
push() adds several elements to the end of Array, and pop() deletes the last element of Array:

var arr = [1, 2];
arr.push('A', 'B'); // 返回Array新的长度: 4arr; // [1, 2, 'A', 'B']arr.pop(); // pop()返回'B'arr; // [1, 2, 'A']arr.pop(); arr.pop(); arr.pop(); // 连续pop 3次arr; // []arr.pop(); // 空数组继续pop不会报错,而是返回undefinedarr; // []
Copy after login


unshift and shift

var arr = [1, 2];
arr.unshift('A', 'B'); // 返回Array新的长度: 4arr; // ['A', 'B', 1, 2]arr.shift(); // 'A'arr; // ['B', 1, 2]arr.shift(); arr.shift(); arr.shift(); // 连续shift 3次arr; // []arr.shift(); // 空数组继续shift不会报错,而是返回undefinedarr; // []
Copy after login

sort
Sort the current Array. It will directly modify the element position of the current Array. When called directly, it will be sorted in the default order:

var arr = ['B', 'C', 'A'];
arr.sort();
arr; // ['A', 'B', 'C']
Copy after login

reverse
Remove all the elements of the entire Array, that is, reverse:

var arr = ['one', 'two', 'three'];
arr.reverse();
arr; // ['three', 'two', 'one']
Copy after login


splice
Modify Array's "universal method", it can delete several elements starting from the specified index, and then add several elements from that position

var arr = ['Microsoft', 'Apple', 'Yahoo', 'AOL', 'Excite', 'Oracle'];// 从索引2开始删除3个元素,然后再添加两个元素:arr.splice(2, 3, 'Google', 'Facebook'); // 返回删除的元素 ['Yahoo', 'AOL', 'Excite']arr; // ['Microsoft', 'Apple', 'Google', 'Facebook', 'Oracle']// 只删除,不添加:arr.splice(2, 2); // ['Google', 'Facebook']arr; // ['Microsoft', 'Apple', 'Oracle']// 只添加,不删除:arr.splice(2, 0, 'Google', 'Facebook'); // 返回[],因为没有删除任何元素arr; // ['Microsoft', 'Apple', 'Google', 'Facebook', 'Oracle']
Copy after login


concat
Convert the current Array Connect with another Array and return a new Array

var arr = ['A', 'B', 'C'];var added = arr.concat([1, 2, 3]);
added; // ['A', 'B', 'C', 1, 2, 3]arr; // ['A', 'B', 'C']
Copy after login


join

var arr = ['A', 'B', 'C', 1, 2, 3];
arr.join('-'); // 'A-B-C-1-2-3'
Copy after login


3.Object
Since JavaScript objects are dynamically typed, you can freely add or delete attributes to an object:

var xiaoming = {
    name: '小明'};
xiaoming.age; // undefinedxiaoming.age = 18; // 新增一个age属性xiaoming.age; // 18delete xiaoming.age; // 删除age属性xiaoming.age; // undefineddelete xiaoming['name']; // 删除name属性xiaoming.name; // undefineddelete xiaoming.school; // 删除一个不存在的school属性也不会报错
Copy after login


To detect whether xiaoming has a certain attribute, you can use the in operation Symbol:

var xiaoming = {
    name: '小明',
    birth: 1990,
    school: 'No.1 Middle School',
    height: 1.70,
    weight: 65,
    score: null};'name' in xiaoming; // true'grade' in xiaoming; // false
Copy after login

But be careful, if in determines that an attribute exists, this attribute does not necessarily belong to xiaoming, it may be inherited from xiaoming:
To determine whether an attribute exists It is owned by xiaoming itself, not inherited. You can use the hasOwnProperty() method:

var xiaoming = {
    name: '小明'};
xiaoming.hasOwnProperty('name'); // truexiaoming.hasOwnProperty('toString'); // false
Copy after login


The ES6 specification introduces new data types Map and Set

var m = new Map([['Michael', 95], ['Bob', 75], ['Tracy', 85]]);
m.get('Michael'); // 95var s1 = new Set(); // 空Setvar s2 = new Set([1, 2, 3]); // 含1, 2, 3
Copy after login


The ES6 standard introduces a new iterable type (can be replaced)
Array, Map and Set all belong to the iterable type.
Traverse through a new for...of loop

var a = ['A', 'B', 'C'];var s = new Set(['A', 'B', 'C']);var m = new Map([[1, 'x'], [2, 'y'], [3, 'z']]);for (var x of a) { // 遍历Array    alert(x);
}for (var x of s) { // 遍历Set    alert(x);
}for (var x of m) { // 遍历Mapalert(x[0] + '=' + x[1]);
}
Copy after login


4. Function
Free keyword arguments, which only works inside the function , and always points to all parameters passed in by the caller of the current function. arguments is like Array but it is not an Array.

function foo(x) {
    alert(x); // 10for (var i=0; i<arguments.length; i++) {
        alert(arguments[i]); // 10, 20, 30    }
}
foo(10, 20, 30);
Copy after login


Max is a JavaScript novice. He wrote a max() function that returns the larger of the two numbers:

document.write(Math.max(7.25,7.30));
Copy after login


5. Variable scope
ES6 introduces the new keyword let. Use let instead of var to declare a block-level variable

&#39;use strict&#39;;function foo() {var sum = 0;for (let i=0; i<100; i++) {
        sum += i;
    }
    i += 1; // SyntaxError}
Copy after login


The ES6 standard introduces a new keyword const to define constants. Both const and let have block-level scope

const PI = 3.14;
PI = 3; // 某些浏览器不报错,但是无效果!PI; // 3.14
Copy after login


6. Advanced functions
map( ) method is defined in JavaScript's Array. We call the map() method of Array, pass in our own function, and get a new Array as the result.

function pow(x) {return x * x;
}var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
arr.map(pow); // [1, 4, 9, 16, 25, 36, 49, 64, 81]
Copy after login


reduce() applies a function to [x1, x2, x3...] of this Array. This function must receive two parameters, reduce() Continue the cumulative calculation of the result with the next element of the sequence. The effect is:

[x1, x2, x3, x4].reduce(f) = f(f(f(x1, x2), x3), x4)var arr = [1, 3, 5, 7, 9];
arr.reduce(function (x, y) {return x + y;
}); // 25
Copy after login


filter is also a commonly used operation. It is used to filter certain elements of Array. drop it, and return the remaining elements.
Apply the passed-in function to each element in turn, and then decide whether to keep or discard the element based on whether the return value is true or false.
For example, in an Array, delete the even numbers and keep only the odd numbers

var arr = [1, 2, 4, 5, 6, 9, 10, 15];var r = arr.filter(function (x) {return x % 2 !== 0;
});
r; // [1, 5, 9, 15]
Copy after login


To delete the empty string in an Array, you can write:

var arr = [&#39;A&#39;, &#39;&#39;, &#39;B&#39;, null, undefined, &#39;C&#39;, &#39;  &#39;];var r = arr.filter(function (s) {return s && s.trim(); // 注意:IE9以下的版本没有trim()方法});
r; // [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;]
Copy after login


Anonymous function (function without function name)

var friends = ["Mike", "Stacy", "Andy", "Rick"];

friends.forEach(function (eachName, index){
console.log(index + 1 + ". " + eachName); // 1. Mike, 2. Stacy, 3. Andy, 4. Rick});
Copy after login


sort sorting algorithm

// 看上去正常的结果:[&#39;Google&#39;, &#39;Apple&#39;, &#39;Microsoft&#39;].sort(); // [&#39;Apple&#39;, &#39;Google&#39;, &#39;Microsoft&#39;];// apple排在了最后:[&#39;Google&#39;, &#39;apple&#39;, &#39;Microsoft&#39;].sort(); // [&#39;Google&#39;, &#39;Microsoft", &#39;apple&#39;]// 无法理解的结果:[10, 20, 1, 2].sort(); // [1, 10, 2, 20]
Copy after login


第二个排序把apple排在了最后,是因为字符串根据ASCII码进行排序,而小写字母a的ASCII码在大写字母之后。
第三个排序结果是什么鬼?简单的数字排序都能错?
这是因为Array的sort()方法默认把所有元素先转换为String再排序,结果'10'排在了'2'的前面,因为字符'1'比字符'2'的ASCII码小。

7闭包
高阶函数除了可以接受函数作为参数外,还可以把函数作为结果值返回

function lazy_sum(arr) {var sum = function () {return arr.reduce(function (x, y) {return x + y;
        });
    }return sum;
}
Copy after login


当我们调用lazy_sum()时,返回的并不是求和结果,而是求和函数:

var f = lazy_sum([1, 2, 3, 4, 5]); // function sum()
Copy after login

调用函数f时,才真正计算求和的结果:

f(); // 15
Copy after login


在函数lazy_sum中又定义了函数sum,并且,内部函数sum可以引用外部函数lazy_sum的参数和局部变量,当lazy_sum返回函数sum时,相关参数和变量都保存在返回的函数中,这种称为“闭包(Closure)”的程序结构拥有极大的威力。

请再注意一点,当我们调用lazy_sum()时,每次调用都会返回一个新的函数,即使传入相同的参数:

var f1 = lazy_sum([1, 2, 3, 4, 5]);var f2 = lazy_sum([1, 2, 3, 4, 5]);
f1 === f2; // false
Copy after login

f1()和f2()的调用结果互不影响。

8.箭头函数
ES6标准新增了一种新的函数:Arrow Function(箭头函数)。
为什么叫Arrow Function?因为它的定义用的就是一个箭头:
x => x * x
上面的箭头函数相当于:

function (x) {return x * x;
}
Copy after login


generator(生成器)是ES6标准引入的新的数据类型。一个generator看上去像一个函数,但可以返回多次。

function* foo(x) {
    yield x + 1;
    yield x + 2;return x + 3;
}
Copy after login

函数在执行过程中,如果没有遇到return语句(函数末尾如果没有return,就是隐含的return undefined;),控制权无法交回被调用的代码。









The above is the detailed content of JavaScript common definitions and methods. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel. How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel. Mar 28, 2024 pm 12:50 PM

Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

How to enter bios on Colorful motherboard? Teach you two methods How to enter bios on Colorful motherboard? Teach you two methods Mar 13, 2024 pm 06:01 PM

Colorful motherboards enjoy high popularity and market share in the Chinese domestic market, but some users of Colorful motherboards still don’t know how to enter the bios for settings? In response to this situation, the editor has specially brought you two methods to enter the colorful motherboard bios. Come and try it! Method 1: Use the U disk startup shortcut key to directly enter the U disk installation system. The shortcut key for the Colorful motherboard to start the U disk with one click is ESC or F11. First, use Black Shark Installation Master to create a Black Shark U disk boot disk, and then turn on the computer. When you see the startup screen, continuously press the ESC or F11 key on the keyboard to enter a window for sequential selection of startup items. Move the cursor to the place where "USB" is displayed, and then

How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) May 01, 2024 pm 12:01 PM

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

How to set font size on mobile phone (easily adjust font size on mobile phone) How to set font size on mobile phone (easily adjust font size on mobile phone) May 07, 2024 pm 03:34 PM

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

Summary of methods to obtain administrator rights in Win11 Summary of methods to obtain administrator rights in Win11 Mar 09, 2024 am 08:45 AM

A summary of how to obtain Win11 administrator rights. In the Windows 11 operating system, administrator rights are one of the very important permissions that allow users to perform various operations on the system. Sometimes, we may need to obtain administrator rights to complete some operations, such as installing software, modifying system settings, etc. The following summarizes some methods for obtaining Win11 administrator rights, I hope it can help you. 1. Use shortcut keys. In Windows 11 system, you can quickly open the command prompt through shortcut keys.

The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) May 04, 2024 pm 06:01 PM

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

Detailed explanation of Oracle version query method Detailed explanation of Oracle version query method Mar 07, 2024 pm 09:21 PM

Detailed explanation of Oracle version query method Oracle is one of the most popular relational database management systems in the world. It provides rich functions and powerful performance and is widely used in enterprises. In the process of database management and development, it is very important to understand the version of the Oracle database. This article will introduce in detail how to query the version information of the Oracle database and give specific code examples. Query the database version of the SQL statement in the Oracle database by executing a simple SQL statement

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

See all articles