Home  >  Article  >  Web Front-end  >  JavaScript common definitions and methods

JavaScript common definitions and methods

巴扎黑
巴扎黑Original
2017-06-26 15:02:011312browse

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; i++) {
        alert(arguments[i]); // 10, 20, 30    }
}
foo(10, 20, 30);


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

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


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 = [&#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;]


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

// 看上去正常的结果:[&#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]


第二个排序把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
Previous article:Detailed explanation of how to change the title of a webpage when it loses focusNext article:Detailed explanation of how to change the title of a webpage when it loses focus

Related articles

See more