search
HomeWeb Front-endJS TutorialSummary of JS array Array methods

Summary of JS array Array methods

Oct 26, 2017 am 10:50 AM
arrayjavascriptarray

1.ArrayArray method

  • ##Mutatormethod———— — "Mutation method" will change the value of the array itself;

  • Accessor method --- "Access method" will not change the value of the array itself;

  • IterationMethod————"Traversal method";

2.

MutatorMethod

  • [ ].pushFunction: Add one or more elements to the end of the array, Pass parameters: (single or multiple array elements); Return value: The length of the new array;

     //标准用法
     arr.push(el1, el2 ……elN);
     //合并两个数组
     [].push.apply(arr1, arr2)

  • [ ].pop(), Function: Delete the last element, Pass parameters: None; Return value: The deleted element.

    //标准用法
    let a = [1 ,2 ,3 ];
    a.pop();//3

  • [ ].unshiftFunction: Add one or more elements to the beginning of the array, Pass parameters : (Single or multiple array elements); Return value : The length of the new array;

     //标准用法
     arr.unshift(el1, el2 ……elN);

  • [].shift() , Function: delete the first element, Pass parameter: None; Return value: deleted element.

    //标准用法
    let a = [1 ,2 ,3 ];
    a.shift();//1

  • [].reverse(), Function: Reverse the position of array elements, Pass parameters: None ;Return value: reversed array.

    //标准用法
    arr.reverse()

  • [].splice(), Function: Reverse the position of array elements, Pass parameters: ( Index, number to delete [select], element to be added [select]); Return value: An array composed of deleted elements.

    //标准用法
    array.splice(start)
    array.splice(start, deleteCount) 
    array.splice(start, deleteCount, item1, item2, ...)

  • [].fill(), Function: Fill an array with a fixed value from the starting index to the ending index All elements within, Pass parameters: (value used to fill array elements, starting index [select], ending index [select]); Return value: modified array .

    //标准用法
    arr.fill(value) 
    arr.fill(value, start) 
    arr.fill(value, start, end)
    //例子
    [1, 2, 3].fill(4)            // [4, 4, 4]
    [1, 2, 3].fill(4, 1)         // [1, 4, 4]
    [1, 2, 3].fill(4, 1, 2)      // [1, 4, 3]

  • [].sort(),Function: Sort the elements of the array and return the array,pass Parameter : (function to specify the sorting order [optional]); Return value : Arranged array.

    //标准用法
    arr.sort() 
    arr.sort(compareFunction)
    //例子
    var numbers = [4, 2, 5, 1, 3];
    numbers.sort(function(a, b) {
    return a - b;
    });// [1, 2, 3, 4, 5]

3.AccessorMethod

    ##①
  • [ ].join

    Function: Join all elements of an array (or an array-like object) into a string. , Pass parameters: (Specify a string to separate each element of the array [select]); Return value: A string concatenating all array elements; <pre class='brush:php;toolbar:false;'>//标准用法 var a = [&amp;#39;Wind&amp;#39;, &amp;#39;Rain&amp;#39;, &amp;#39;Fire&amp;#39;]; var myVar1 = a.join(); // myVar1的值变为&quot;Wind,Rain,Fire&quot; var myVar2 = a.join(&amp;#39;, &amp;#39;); // myVar2的值变为&quot;Wind, Rain, Fire&quot;</pre>

  • [ ].concat

    Function: Concatenate two or more arrays. ,Passing parameters: (Connect arrays and/or values ​​into a new array [select]);Return value: Merged array;<pre class='brush:php;toolbar:false;'>//标准用法 var alpha = [&amp;#39;a&amp;#39;, &amp;#39;b&amp;#39;, &amp;#39;c&amp;#39;]; var numeric = [1, 2, 3]; alpha.concat(numeric); //[&amp;#39;a&amp;#39;, &amp;#39;b&amp;#39;, &amp;#39;c&amp;#39;, 1, 2, 3]</pre>

  • [ ].slice

    Function: The method returns a shallow copy of a part of the selected array from the beginning to the end (excluding the end) to a new array. , Pass parameters: (Start index [select], End index [select]); Return value: Truncated array; <pre class='brush:php;toolbar:false;'>//标准用法 var fruits = [&amp;#39;Banana&amp;#39;, &amp;#39;Orange&amp;#39;, &amp;#39;Lemon&amp;#39;, &amp;#39;Apple&amp;#39;, &amp;#39;Mango&amp;#39;]; var citrus = fruits.slice(1, 3); //[&amp;#39;Orange&amp;#39;,&amp;#39;Lemon&amp;#39;] //类数组转数组 function list() { return [].slice.call(arguments)} var list1 = list(1, 2, 3); // [1, 2, 3]</pre>

  • [ ].toString

    Function: Return a string representing the specified array and its elements, Pass parameters: (none);Return value: Converted string; (=[].join())<pre class='brush:php;toolbar:false;'>//标准用法 var monthNames = [&amp;#39;Jan&amp;#39;, &amp;#39;Feb&amp;#39;, &amp;#39;Mar&amp;#39;, &amp;#39;Apr&amp;#39;]; var myVar = monthNames.toString(); // assigns &quot;Jan,Feb,Mar,Apr&quot; to myVar.</pre>

  • [ ].includes

    Function: Determine whether an array contains a specified value, Pass parameters: (the element to be found); Return value: true or false; <pre class='brush:php;toolbar:false;'>//标准用法 let a = [1, 2, 3]; a.includes(2); // true a.includes(4); // false</pre>

  • [ ].indexOf

    Function: The first index of a given element can be found in the array, Pass parameters: (element to be found); Return value: Not found -1, index found; <pre class='brush:php;toolbar:false;'>var array = [2, 5, 9]; array.indexOf(2); // 0 array.indexOf(7); // -1</pre>

4.

IterationMethod


  • ##①
      [ ].forEach
    • Function: Each element executes the provided function once, Pass parameters: (callback(current element, index, the array));Return value: None;

       //标准用法
       array.forEach(callback(currentValue, index, array){
       //do something
      }, this)

    • [ ].find
    • Function: Return the array that satisfies the provided test The value of the first element of the function, Pass parameters: (callback(current element, index, the array)); Return value: The element; ([]. findIndex()Return index)

       //标准用法
       array. find(callback(currentValue, index, array){
       //do something
      }, this)

    • [ ].filter
    • Function: Create a new array containing All elements of the test implemented by the provided function, Pass parameters: (callback(current element, index, the array)); Return value: Array of the collection of elements that pass the test;

       //标准用法
       let arr = array. filter(callback(currentValue, index, array){
       //do something
       }, this)
    • [ ].map作用:创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。,传参:(callback(当前元素,索引,该数组));返回值:一个新数组,每个元素都是回调函数的结果;

       //标准用法
       var numbers = [1, 4, 9];
       var roots = numbers.map(Math.sqrt);
       // roots的值为[1, 2, 3], numbers的值仍为[1, 4, 9]
    • [ ].every作用:测试数组的所有元素是否都通过了指定函数的测试;传参:(callback(当前元素,索引,该数组));返回值truefalse

         //标准用法
         function isBigEnough(element, index, array) {
          return (element >= 10);}
         var passed = [12, 5, 8, 130, 44].every(isBigEnough);// passed is false
         passed = [12, 54, 18, 130, 44].every(isBigEnough);// passed is true
    • [ ].some作用:测试数组的某些元素是否都通过了指定函数的测试;传参:(callback(当前元素,索引,该数组));返回值truefalse

         //标准用法
         function isBigEnough(element, index, array) {
          return (element >= 10);}
         var passed = [1, 5, 8, 3, 4].some(isBigEnough);// passed is false
         passed = [2, 4, 18, 13, 4].some(isBigEnough);// passed is true
    • [ ].reduce作用:对累加器和数组中的每个元素(从左到右)应用一个函数,将其减少为单个值;传参:(callback(累加器accumulator,当前元素,索引,该数组));返回值:函数累计处理的结果;

         //标准用法
         var total = [0, 1, 2, 3].reduce(function(sum, value) {
          return sum + value;
        }, 0);// total is 6
      
         var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
          return a.concat(b);}, []);
          // flattened is [0, 1, 2, 3, 4, 5]
    • [ ].entries作用:返回一个新的Array Iterator对象,该对象包含数组中每个索引的键/值对;传参:(无));返回值:一个新的 Array 迭代器对象;

         //标准用法
         var arr = ["a", "b", "c"];
         var iterator = arr.entries();// undefined
         console.log(iterator);// Array Iterator {}
         console.log(iterator.next().value); // [0, "a"]
         console.log(iterator.next().value); // [1, "b"]
         console.log(iterator.next().value); // [2, "c"]
    • [ ].values作用:数组转对象;传参:(无));返回值:一个新的 Array 迭代器对象;

         //标准用法
         let arr = [&#39;w&#39;, &#39;y&#39;, &#39;k&#39;, &#39;o&#39;, &#39;p&#39;];
         let eArr = arr.values();// 您的浏览器必须支持 for..of 循环
         // 以及 let —— 将变量作用域限定在 for 循环中
        for (let letter of eArr) {
               console.log(letter);}

    参考资料:https://developer.mozilla.org...


    1.Array数组的方法

    • Mutator方法————"突变方法"会改变数组自身的值;

    • Accessor方法————"访问方法"不会改变数组自身的值;

    • Iteration方法————"遍历的方法" ;

    2.Mutator方法

    • [ ].push作用:将一个或多个元素添加到数组的末尾,传参:(单个或多个数组元素);返回值:新数组的长度;

       //标准用法
       arr.push(el1, el2 ……elN);
       //合并两个数组
       [].push.apply(arr1, arr2)
    • [].pop()作用:删除最后一个元素,传参:无;返回值:删除的元素。

      //标准用法
      let a = [1 ,2 ,3 ];
      a.pop();//3
    • [ ].unshift作用:将一个或多个元素添加到数组的开头,传参:(单个或多个数组元素);返回值:新数组的长度;

       //标准用法
       arr.unshift(el1, el2 ……elN);
    • [].shift()作用:删除第一个元素,传参:无;返回值:删除的元素。

      //标准用法
      let a = [1 ,2 ,3 ];
      a.shift();//1
    • [].reverse()作用:数组元素颠倒位置,传参:无;返回值:颠倒后的数组。

      //标准用法
      arr.reverse()
    • [].splice()作用:数组元素颠倒位置,传参:(索引,删除个数【选】,要添加的元素【选】);返回值:被删除的元素组成的一个数组。

      //标准用法
      array.splice(start)
      array.splice(start, deleteCount) 
      array.splice(start, deleteCount, item1, item2, ...)
    • [].fill()作用:用一个固定值填充一个数组中从起始索引到终止索引内的全部元素,传参:(用来填充数组元素的值,起始索引【选】,终止索引【选】);返回值:修改后的数组。

      //标准用法
      arr.fill(value) 
      arr.fill(value, start) 
      arr.fill(value, start, end)
      //例子
      [1, 2, 3].fill(4)            // [4, 4, 4]
      [1, 2, 3].fill(4, 1)         // [1, 4, 4]
      [1, 2, 3].fill(4, 1, 2)      // [1, 4, 3]
    • [].sort()作用:对数组的元素进行排序,并返回数组,传参:(指定排列顺序的函数【选】);返回值:排列后的数组。

      //标准用法
      arr.sort() 
      arr.sort(compareFunction)
      //例子
      var numbers = [4, 2, 5, 1, 3];
      numbers.sort(function(a, b) {
      return a - b;
      });// [1, 2, 3, 4, 5]

    3.Accessor方法

    • [ ].join作用:将数组(或一个类数组对象)的所有元素连接到一个字符串中。,传参:(指定一个字符串来分隔数组的每个元素【选】);返回值:一个所有数组元素连接的字符串;

      <pre class='brush:php;toolbar:false;'>//标准用法 var a = [&amp;#39;Wind&amp;#39;, &amp;#39;Rain&amp;#39;, &amp;#39;Fire&amp;#39;]; var myVar1 = a.join(); // myVar1的值变为&quot;Wind,Rain,Fire&quot; var myVar2 = a.join(&amp;#39;, &amp;#39;); // myVar2的值变为&quot;Wind, Rain, Fire&quot;</pre>
    • [ ].concat作用:并两个或多个数组。,传参:(将数组和/或值连接成新数组【选】);返回值:合并后的数组;

      //标准用法
      var alpha = ['a', 'b', 'c'];
      var numeric = [1, 2, 3];
      alpha.concat(numeric);
      //['a', 'b', 'c', 1, 2, 3]
    • [ ].slice作用:方法返回一个从开始到结束(不包括结束)选择的数组的一部分浅拷贝到一个新数组。,传参:(开始索引【选】,结束索引【选】);返回值:截去后的数组;

      <pre class='brush:php;toolbar:false;'>//标准用法 var fruits = [&amp;#39;Banana&amp;#39;, &amp;#39;Orange&amp;#39;, &amp;#39;Lemon&amp;#39;, &amp;#39;Apple&amp;#39;, &amp;#39;Mango&amp;#39;]; var citrus = fruits.slice(1, 3); //[&amp;#39;Orange&amp;#39;,&amp;#39;Lemon&amp;#39;] //类数组转数组 function list() { return [].slice.call(arguments)} var list1 = list(1, 2, 3); // [1, 2, 3]</pre>
    • [ ].toString作用:返回一个字符串,表示指定的数组及其元素,传参:(无);返回值:转化成的字符串;(=[].join()

      <pre class='brush:php;toolbar:false;'>//标准用法 var monthNames = [&amp;#39;Jan&amp;#39;, &amp;#39;Feb&amp;#39;, &amp;#39;Mar&amp;#39;, &amp;#39;Apr&amp;#39;]; var myVar = monthNames.toString(); // assigns &quot;Jan,Feb,Mar,Apr&quot; to myVar.</pre>
    • [ ].includes作用:判断一个数组是否包含一个指定的值,传参:(要查找的元素);返回值:true或 false;

      <pre class='brush:php;toolbar:false;'>//标准用法 let a = [1, 2, 3]; a.includes(2); // true a.includes(4); // false</pre>
    • [ ].indexOf作用:在数组中可以找到一个给定元素的第一个索引,传参:(要查找的元素);返回值:找不到-1,找得到索引;

      <pre class='brush:php;toolbar:false;'>var array = [2, 5, 9]; array.indexOf(2); // 0 array.indexOf(7); // -1</pre>

    4.Iteration方法


    • [ ].forEach作用:每个元素执行一次提供的函数,传参:(callback(当前元素,索引,该数组));返回值:无;

       //标准用法
       array.forEach(callback(currentValue, index, array){
       //do something
      }, this)
    • [ ].find作用:返回数组中满足提供的测试函数的第一个元素的值,传参:(callback(当前元素,索引,该数组));返回值:该元素;([].findIndex()返回索引)

       //标准用法
       array. find(callback(currentValue, index, array){
       //do something
      }, this)
    • [ ].filter作用:创建一个新数组, 其包含通过所提供函数实现的测试的所有元素,传参:(callback(当前元素,索引,该数组));返回值:通过测试的元素的集合的数组;

       //标准用法
       let arr = array. filter(callback(currentValue, index, array){
       //do something
       }, this)
    • [ ].map作用:创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。,传参:(callback(当前元素,索引,该数组));返回值:一个新数组,每个元素都是回调函数的结果;

       //标准用法
       var numbers = [1, 4, 9];
       var roots = numbers.map(Math.sqrt);
       // roots的值为[1, 2, 3], numbers的值仍为[1, 4, 9]
    • [ ].every作用:测试数组的所有元素是否都通过了指定函数的测试;传参:(callback(当前元素,索引,该数组));返回值truefalse

         //标准用法
         function isBigEnough(element, index, array) {
          return (element >= 10);}
         var passed = [12, 5, 8, 130, 44].every(isBigEnough);// passed is false
         passed = [12, 54, 18, 130, 44].every(isBigEnough);// passed is true
    • [ ].some作用:测试数组的某些元素是否都通过了指定函数的测试;传参:(callback(当前元素,索引,该数组));返回值truefalse

         //标准用法
         function isBigEnough(element, index, array) {
          return (element >= 10);}
         var passed = [1, 5, 8, 3, 4].some(isBigEnough);// passed is false
         passed = [2, 4, 18, 13, 4].some(isBigEnough);// passed is true
    • [ ].reduce作用:对累加器和数组中的每个元素(从左到右)应用一个函数,将其减少为单个值;传参:(callback(累加器accumulator,当前元素,索引,该数组));返回值:函数累计处理的结果;

         //标准用法
         var total = [0, 1, 2, 3].reduce(function(sum, value) {
          return sum + value;
        }, 0);// total is 6
      
         var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
          return a.concat(b);}, []);
          // flattened is [0, 1, 2, 3, 4, 5]
    • [ ].entries作用:返回一个新的Array Iterator对象,该对象包含数组中每个索引的键/值对;传参:(无));返回值:一个新的 Array 迭代器对象;

         //标准用法
         var arr = ["a", "b", "c"];
         var iterator = arr.entries();// undefined
         console.log(iterator);// Array Iterator {}
         console.log(iterator.next().value); // [0, "a"]
         console.log(iterator.next().value); // [1, "b"]
         console.log(iterator.next().value); // [2, "c"]
    • [ ].values作用:数组转对象;传参:(无));返回值:一个新的 Array 迭代器对象;

         //标准用法
         let arr = [&#39;w&#39;, &#39;y&#39;, &#39;k&#39;, &#39;o&#39;, &#39;p&#39;];
         let eArr = arr.values();// 您的浏览器必须支持 for..of 循环
         // 以及 let —— 将变量作用域限定在 for 循环中
        for (let letter of eArr) {
               console.log(letter);}


The above is the detailed content of Summary of JS array Array 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
Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

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.

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

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.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software