Arrays in JavaScript are very special. Unlike C or Java, which have a whole set of arrays and lists, arrays in JS can be used as a stack or queue. Four Big operations pop, push, shift, unshift.
For an array method, there are two issues that we are most concerned about. What is the return value and whether it will affect the original array , typical examples are the splice and slice methods. For functions that return the original array, we can chain calls directly to the array, which is pretty cool (array.filter().sort().reverse()).
I would like to summarize the array method of Array with these two questions.
Array
Array.length is the length of the array. Each newly created array object will have a length object. The prototype can be modified through Array.prototype, but the basic use and operation of arrays are not what they are today. Focus, let's look at the array method.
Generally, array methods will have a thisArg parameter at the end, which will specify the internal this pointer. If there is a fallback function in the parameters, this fallback function generally accepts three parameters, value, index and array, which respectively represent the currently passed in value, the index where the currently passed in value is located and the current processed array.
Directory index:
concat
This method can be used to splice arrays. The parameter is one or more arrays, and the returned result is a spliced array.
The concat method will create a new array, and then call it with the elements in the object (the object pointed to by this, the original array) and the elements in the array type parameters of all parameters and non-array types. The parameters themselves are put into this new array in order, and that array is returned. The concat method does not modify the original array and parameter array, and has the same effect on non-array objects.
Return the spliced new array;
Do not modify the original array and parameter array;
Parameters can be non-arrays.
var a1 = [1, 2, 3], a2 = [4, 5, 6], a3 = [7, 8, 9]; var newarr = a1.concat(a2, a3); newarr //[1, 2, 3, 4, 5, 6, 7, 8, 9] a1 //[1, 2, 3] newarr = a1.concat(4, a3);//[1, 2, 3, 4, 7, 8, 9] newarr = a1.concat('hello');//[1, 2, 3, "hello"] |
- If all tests pass, the function returns the value true. If it exits halfway, it returns false;
- will not affect the original array.
- will not change the original array.
##forEach |
The function has no return value, that is, underfined;
has no effect on the original array.
- ##
function logArrayElements(element, index, array) { console.log("a[" + index + "] = " + element); } // 注意索引2被跳过了,因为在数组的这个位置没有项 var result = [2, 5, 9].forEach(logArrayElements); // a[0] = 2 // a[1] = 5 // a[2] = 9 result //underfined
indexOf() method returns to The specified element can be found at the first index value found in the array, otherwise -1 is returned. |
The return value is the index value of the found element or -1;
- does not affect the original array.
-
var array = [1, 2, 5]; array.indexOf(5); // 2 array.indexOf(7); // -1
join The join() method joins all the elements in the array into a string.
In fact, the first thing that comes to mind for join is the split operation of strings. These two are often used together to process strings.
Returns the concatenated string;
- does not affect the original array.
-
var a1 = [1, 2, 3]; var a2 = a1.join(); a1 //[1, 2, 3] a2 //"1,2,3" a2 = a1.join("");//"123" a2 = a1.join("-");//"1-2-3"
lastIndexOf() method returns the specified The index of the last element (that is, a valid JavaScript value or variable) in the array, or -1 if it does not exist. Search forward from the back of the array, starting from fromIndex. |
-
var array = [2, 5, 9, 2]; var index = array.lastIndexOf(2); // index is 3 index = array.lastIndexOf(7); // index is -1 index = array.lastIndexOf(2, 3); // index is 3 index = array.lastIndexOf(2, 2);
var a1 = [1, 4, 9]; var a2 = a1.map(Math.sqrt); a1 //[1, 4, 9] a2 //[1, 2, 3] |
reduce
reduce() 方法接收一个函数作为累加器(accumulator),数组中的每个值(从左到右)开始合并,最终为一个值。
reduce 是一个合并的过程,从左到右,直到把所有元素合并到一起,并返回最终的结果。它接受两个参数,第一个参数是一个回掉函数,第二个参数是一个初始值,表示处理第一个元素时的前一个值。这个回掉函数接受四个参数,依次是 accumulator(上次处理的结果),currentValue(当前元素的值),index(当前元素索引),array(调用 reduce 的数组)。
返回最终合并的结果,即回掉函数的输出,可以为字符串,对象,数组等任意结果;
不对原数组产生影响。
var getAdd = (pre, cur) => pre + cur; var a1 = [1, 2, 3]; var a2 = a1.reduce(getAdd, 0); a1 //[1, 2, 3] a2 //6 |
reduceRight
reduceRight() 方法接受一个函数作为累加器(accumulator),让每个值(从右到左,亦即从尾到头)缩减为一个值。(与 reduce() 的执行方向相反)
var toStr = (pre, cur) => '' + pre + cur; var a1 = [1, 2, 3]; var a2 = a1.reduce(toStr, ''); a2 //"123" a2 = a1.reduceRight(toStr, ''); a2 //"321" |
push
push() 方法添加一个或多个元素到数组的末尾,并返回数组新的长度(length 属性值)。
如果把数组当作栈,push pop 操作是栈进和出,而往往很多人会忽略函数执行后的返回值。
返回 push 操作执行之后数组的长度;
肯定改变。
var a1 = [1, 2, 3]; var a2 = a1.push(4); a1 //[1, 2, 3, 4] a2 //4 |
pop
pop() 方法删除一个数组中的最后的一个元素,并且返回这个元素。
返回删除的这个元素;
肯定改变。
var a1 = [1, 2, 3]; var a2 = a1.pop(); a1 //[1, 2] a2 //3 |
unshift
unshift() 方法在数组的开头添加一个或者多个元素,并返回数组新的 length 值。
返回 length 值;
肯定改变。
var a1 = [1, 2, 3]; var a2 = a1.unshift(4); a1 //[4, 1, 2, 3] a2 //4 |
shift
shift() 方法删除数组的 第一个 元素,并返回这个元素。该方法会改变数组的长度。
shift 方法和 push 方法可以组成一个队列的操作啦。
返回删除的这个元素;
肯定改变。
reverse
reverse() 方法颠倒数组中元素的位置。第一个元素会成为最后一个,最后一个会成为第一个。
函数返回值是修改了的原数组;
原数组会修改。
var a1 = [1, 2, 3]; var a2 = a1.reverse(); a1 //[3, 2, 1] a1 === a2; //true |
slice
slice() 方法会浅复制(shallow copy)数组的一部分到一个新的数组,并返回这个新数组。
slice 的参数包括拷贝的初识位置,结束位置(左闭右开),与 splice 有区别。由于不会改变原数组,这个数组可以用于前拷贝,比如经常看别人使用: arr.slice(0) ,表示拷贝数组。
返回浅拷贝后的新数组;
不会改变原数组。
var a1 = [1, 2, 3, 4, 5]; var a2 = a1.slice(1, 3); a1 //[1, 2, 3, 4, 5] a2 //[2, 3] |
splice
splice() 方法用新元素替换旧元素,以此修改数组的内容。
如其名,分割,会修改原数组的内容,返回一个新数组,而且它的参数也比较多,第一个参数表示初始位置,第二个参数表示分割长度,第三个参数及以后表示分割后在分割处添加新元素。
返回分割的元素组成的数组;
会对数组进行修改,原数组会减去分割数组。
var a1 = [1, 2, 3, 4]; var a2 = a1.splice(1, 2); a1 //[1, 4] a2 //[2, 3] a1 = [1, 2, 3, 4]; a2 = a1.splice(1, 2, 5, 6); a1 //[1, 5, 6, 4] |
some
some() 方法测试数组中的某些元素是否通过了指定函数的测试。
sort
sort() 方法对数组的元素做原地的排序,并返回这个数组。 sort 排序可能是不稳定的。默认按照字符串的Unicode码位点(code point)排序。
sort 函数用于排序,比较常用,若没有制定排序函数,则按照 unicode 位点进行排序,而且数字会被转成字符串,所以 ‘123’ 要排在 ‘11’ 的后面。
我们会用 sort 做一些有意思的排序,比如汉字按照拼音排序。
返回排序后的原数组;
会对数组进行修改。
var big = function(a, b){ return a - b; } var a1 = [2, 4, 77, 1]; var a2 = a1.sort(big); a1 //[1, 2, 4, 77] a1 === a2; //true |
localeCompare 可以对汉字进行排序,当同时出现汉字和字母的时候会有 bug:
var sort_py = function(a, b){ return a.localeCompare(b); } var a1 = ["北京", "上海", "南京", "合肥"]; a1.sort(sort_py); //["北京", "合肥", "南京", "上海"] |
toString
toString() 返回一个字符串,表示指定的数组及其元素。
显然,这个方法和 join 方法比较一下。
返回拼接的字符串;
不会改变原数组。
var a1 = [1, 2, 3]; var a2 = a1.toString(); a2 //"1,2,3"
ES6 中新添的数组方法
上面的这些方法都是 ES5 的,来看看 ES6 添加了哪些新方法。
copyWithin
copyWithin() 方法会浅拷贝数组的部分元素到同一数组的不同位置,且不改变数组的大小,返回该数组。
接受三个参数,分别是要拷贝到的位置 target,拷贝开始位置 start 和结束位置 end。
返回修改了的原数组;
会对数组进行修改,且是浅拷贝;
参数可负,负值时倒推,且 end 为空表示数组长度。
var a1 = [1, 2, 3, 4, 5]; var a2 = a1.copyWithin(0, 2, 4); a1 //[3, 4, 3, 4, 5] a2 //[3, 4, 3, 4, 5] a1 === a2; //true |
find
如果数组中某个元素满足测试条件,find() 方法就会返回满足条件的第一个元素,如果没有满足条件的元素,则返回 undefined。 MDN array.find 。
返回找到的那个元素,若未找到,返回 underfined
不对原数组产生影响。
function isBigEnough(element, index, array) { return (element >= 10); } var a1 = [8, 18, 14]; var num = a1.find(isBigEnough); //18 |
findIndex
findIndex()方法用来查找数组中某指定元素的索引, 如果找不到指定的元素, 则返回 -1。
这个方法可以参考 find 方法,只是返回值是元素的索引而非元素本身。
fill
使用 fill() 方法,可以将一个数组中指定区间的所有元素的值, 都替换成或者说填充成为某个固定的值。
fill 方法接受三个参数,第一个参数 value 表示要填充到值,后面两个 start 和 end 表示开始和结束位置,可选,且左闭右开。
函数返回值是修改了的原数组;
可对数组产生影响。
var a1 = [1, 2, 3, 4, 5]; var a2 = a1.fill(6, 1, 4); a1 //[1, 6, 6, 6, 5] a2 //[1, 6, 6, 6, 5] a1 === a2; //true |
keys
数组的 keys() 方法返回一个数组索引的迭代器。
这个方法会返回一个数组索引的迭代器,迭代器在 ES6 中有特殊的用途。
函数返回一个迭代器对象;
不会改变原数组。
var arr = ["a", "b", "c"]; var iterator = arr.keys(); console.log(iterator.next()); // { value: 0, done: false } console.log(iterator.next()); // { value: 1, done: false } console.log(iterator.next()); // { value: 2, done: false } console.log(iterator.next()); // { value: undefined, done: true } |
entries
entries() 方法返回一个 Array Iterator 对象,该对象包含数组中每一个索引的键值对。
var arr = ["a", "b", "c"]; var eArr = arr.entries(); console.log(eArr.next().value); // [0, "a"] console.log(eArr.next().value); // [1, "b"] console.log(eArr.next().value); // [2, "c"] |
includes
includes() 方法用来判断当前数组是否包含某指定的值,如果是,则返回 true,否则返回 false。
该函数接受两个参数,第二个参数表示开始查找位置,起始位置为 0。这个方法与 indexOf 方法最大的区别不仅在于返回值一个是索引,一个是布尔值,indexOf 方法使用的是 === 来判断,无法判断 NaN 情况,而 includes 可以判断。
返回 true 或 false;
不会改变原数组。
var a1 = [1, NaN]; a1.indexOf(NaN);//-1 a1.includes(NaN);//true

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

Matter.js is a 2D rigid body physics engine written in JavaScript. This library can help you easily simulate 2D physics in your browser. It provides many features, such as the ability to create rigid bodies and assign physical properties such as mass, area, or density. You can also simulate different types of collisions and forces, such as gravity friction. Matter.js supports all mainstream browsers. Additionally, it is suitable for mobile devices as it detects touches and is responsive. All of these features make it worth your time to learn how to use the engine, as this makes it easy to create a physics-based 2D game or simulation. In this tutorial, I will cover the basics of this library, including its installation and usage, and provide a

This article demonstrates how to automatically refresh a div's content every 5 seconds using jQuery and AJAX. The example fetches and displays the latest blog posts from an RSS feed, along with the last refresh timestamp. A loading image is optiona


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 English version
Recommended: Win version, supports code prompts!

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools