search
HomeWeb Front-endJS TutorialJavaScript common definitions and methods

JavaScript common definitions and methods

Jun 26, 2017 pm 03:02 PM
javascriptjsCommonly usedmethod

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'


toLowerCase()
Change a string to all lowercase:

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


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

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


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'


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


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']

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; // []


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; // []

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']

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

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


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']


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']


join

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


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属性也不会报错


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

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


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


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]);
}


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 foo></arguments.length>


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));


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

'use strict';function foo() {var sum = 0;for (let i=0; i


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


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]


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


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]


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

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


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});


sort sorting algorithm

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


第二个排序把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;
}


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

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

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

f(); // 15


在函数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

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

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

function (x) {return x * x;
}


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

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

函数在执行过程中,如果没有遇到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
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
Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

See all articles

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools