Home Web Front-end JS Tutorial How to use array functions in JS

How to use array functions in JS

Jun 22, 2018 pm 04:50 PM
js array function

The editor of this article has compiled a very comprehensive list of JS array functions and related writing rules for you. I hope it can be helpful and reference for readers.

Script House has compiled content related to JS arrays before. This time we have compiled very practical JS array operation techniques and writing methods for you. Let’s learn from them.

instanceof

检测一个对象是否是数组;(用来对付复杂数据类型;)
// 简单数据类型 typeof ;
A instanceof B // A是不是B造出来的;
例:
  var arr = [1,2,3];
  console.log(arr instanceof Array); //arr属不属于Array类型;
Copy after login

Array.isArray( )

Array.isArray(参数); // 判断参数是不是数组,返回布尔值;
例:
  var arr = [1,2,3];
  var num = 123;
  console.log(Array.isArray(arr)); //true
  console.log(Array.isArray(num)); //false
Copy after login

toString( )

数组.toString(); // 把数组变成字符串,去除了[],内容用逗号链接;
例:
  var arr = ["aaa","bbb","ccc"];
  console.log(arr.toString());   //返回 aaa,bbb,ccc
Copy after login

valueOf( )

数组.valueOf(); //返回数组本身;  
例:
  var arr = ["aaa","bbb","ccc"];
  console.log(arr.valueOf());   //返回数组本身 ["aaa","bbb","ccc"]
Copy after login

array.join( Parameters)

数组.join(参数); // 数组中的元素可以按照参数进行链接变成一个字符串;
console.log(arr.join()); //和toString()一样用逗号链接
console.log(arr.join("|")); //用参数链接
console.log(arr.join("&")); //用参数链接
console.log(arr.join(" ")); //如果是空格,真的用空格链接
console.log(arr.join("")); //空字符是无缝连接
Copy after login

Addition and deletion of array elements

push( ) and pop( )

1. 数组.push() //在数组的最末尾添加元素;
2. 数组.pop() //不需要参数;在数组的最末尾删除一项;
例:
  var arr = [1,2,3];
  var aaa = arr.push("abc");//在数组的最末尾添加一个元素;
  console.log(arr);//元素被修改了
  console.log(aaa);//返回值是数组的长度;

  aaa = arr.pop();//不需要参数;在数组的最末尾删除一项;
  console.log(arr);//元素被修改了
  console.log(aaa);//被删除的那一项
Copy after login

unshift( ) and shift( )

1. 数组.unshift() //在数组的最前面添加一个元素;
2. 数组.shift() //不需要参数;在数组的最前面删除一项;
例:
  var arr = [1,2,3];
  aaa = arr.unshift("abc");//在数组的最前面添加一个元素;
  console.log(arr);//元素被修改了
  console.log(aaa);//返回值是数组的长度;

  aaa = arr.shift();//不需要参数;在数组的最前面删除一项;
  console.log(arr);//元素被修改了
  console.log(aaa);//被删除的那一项
Copy after login

Array element sorting

reverse( )

reverse()  //翻转数组
例:
  var arr1 = [1,2,3,4,5];
  var aaa = arr1.reverse(); // [5,4,3,2,1]
Copy after login

sort( )

sort() // 数组中元素排序;(默认:从小到大)
   // 默认:按照首个字符的Unicode编码排序;如果第一个相同那么就比较第二个...
例:    
  var arr = [4,5,1,3,2,7,6];
  var aaa =arr.sort();
  console.log(aaa);     // [1, 2, 3, 4, 5, 6, 7]
  console.log(aaa === arr);// true 原数组被排序了(冒泡排序)
  //默认还可以排列字母;
  var arr2 = ["c","e","d","a","b"];
  var bbb = arr2.sort();
  console.log(bbb);     // ["a", "b", "c", "d", "e"]
  console.log(bbb===arr2); // true 原数组被排序了(冒泡排序)

sort() //数值大小排序方法,需要借助回调函数;
例:
   var arr = [4,5,1,13,2,7,6];
   //回调函数里面返回值如果是:参数1-参数2;升幂;  参数2-参数1;降幂;
   arr.sort(function (a,b) {
    return a-b; //升序
    //return b-a; //降序
    //return b.value-a.value; //按照元素value属性的大小排序;
   });
   console.log(arr); // [1, 2, 4, 5, 6, 7, 13]
Copy after login

sort( ) underlying principle

  var aaa = bubbleSort([1,12,3], function (a,b) {
//    return a-b;//实参:array[j]-array[j+1];
    return b-a;//实参:array[j+1]-array[j];
  });
  console.log(aaa);

  function bubbleSort(array,fn){
    //外循环控制轮数,内循环控制次数,都是元素个数-1;
    for(var i=0;i<array.length-1;i++){
      for(var j=0;j<array.length-1-i;j++){//次数优化,多比较一轮,少比较一次;
        //满足条件交换位置;
//        if(array[j]>array[j+1]){//大于升幂排序;否则降幂;
        //a-b>0 和 a>b是一个意思;
        //b-a>0 和 a<b是一个意思;
//        if(array[j]-array[j+1]>0){//升幂排序
//        if(array[j+1]-array[j]>0){//降幂排序
        //把两个变量送到一个函数中;
        if(fn(array[j],array[j+1])>0){
          var temp = array[j];
          array[j] = array[j+1];
          array[j+1] = temp;
        }
      }
    }
    //返回数组
    return array;
  }
Copy after login

Operations of array elements

concat( )

数组1.concat(数组2); // 链接两个数组;
var arr1 = [1,2,3];
var arr2 = ["a","b","c"];
var arr3 = arr1.concat(arr2);
console.log(arr3)  //  [1, 2, 3, "a", "b", "c"]
Copy after login

slice( )

数组.slice(开始索引值,结束索引值);   //数组截取;
例 :
   var arr = [1, 2, 3, "a", "b", "c"];
   console.log(arr.slice(3));      //从索引值为3截取到最后;["a", "b", "c"]
   console.log(arr.slice(0,3));      //包左不包右;[1, 2, 3]
   console.log(arr.slice(-2));      //负数是后几个;["b", "c"]
   console.log(arr.slice(3,0));      //如果前面的比后面的大,那么就是[];[]
   console.log(arr);             //原数组不被修改;[1, 2, 3, "a", "b", "c"]
Copy after login

splice( )

数组.splice(开始索引值,删除几个,替换内容1,替换内容2,...); // 替换和删除;
                           //改变原数组;返回值是被删除/替换的内容
例:
  var arr = [1,2,3,4,5,6,"a", "b", "c"]
  arr.splice(5);    //从索引值为3截取到最后;(删除)
  console.log(arr);   // [1, 2, 3, 4, 5]
  arr.splice(1,2);  //(删除指定个数)从索引为1的开始删除2个
  console.log(arr);  //[1, 4, 5]

//替换
  var arr = [1,2,3,4,5,6,"a", "b", "c"];
  console.log(arr.splice(3,3,"aaa","bbb","ccc"));  //(删除指定数并替换)
  console.log(arr);   // [1, 2, 3, "aaa", "bbb", "ccc", "a", "b", "c"]
//  添加
  arr.splice(3,0,"aaa","bbb","ccc");//(删除指定个数)
//
  console.log(arr);//截取或者替换之后的;  [1, 2, 3, "aaa", "bbb", "ccc", "aaa", "bbb", "ccc", "a", "b", "c"]
Copy after login

indexOf / lastIndexOf

数组.indexOf(元素);   // 给元素,查索引(从前往后)
数组.lastIndexOf(元素); // 给元素,查索引(从后往前)
例:
  var arr = ["a","b","c","d","c","b","b"];
  console.log(arr.indexOf("b"));    // 1 查到以后立刻返回
  console.log(arr.lastIndexOf("b"));  // 6 找到以后立刻返回
  console.log(arr.indexOf("xxx"));  // -1; 查不到就返回-1;
Copy after login

Array iteration (traversal)

every()

对数组中每一项运行回调函数,如果都返回true,every返回true,
如果有一项返回false,则停止遍历 every返回false;不写默认返回false
像保镖失误一次,游戏结束!!!
例:
1.  var arr = [111,222,333,444,555];
  arr.every(function (a,b,c) {
    console.log(a);  //元素
    console.log(b);  //索引值
    console.log(c);  //数组本身;
    console.log("-----");  //数组本身;
    //数组中元素赋值:c[b] = 值;   a=有时候无法赋值;
    return true;
  });

2. //every返回一个bool值,全部是true才是true;有一个是false,结果就是false
  var bool = arr.every(function (element, index, array) {
    //判断:我们定义所有元素都大于200;
    //if(element > 100){
    if(element > 200){
      return true;
    }else{
      return false;
    }
  })
  alert(bool); //false
Copy after login

filter()

//  对数组中每一项运行回调函数,该函数返回结果是true的项组成的新数组
//   新数组是有老数组中的元素组成的,return为ture的项;
例:
  var arr = [111,222,333,444,555];
  var newArr = arr.filter(function (element, index, array) {
    //只要是奇数,就组成数组;(数组中辨别元素)
    if(element%2 === 0){
      return true;
    }else{
      return false;
    }
  })

  console.log(newArr); // [222, 444]
Copy after login

forEach()

// 和for循环一样;没有返回值;
例:
  var arr = [111,222,333,444,555];
  var sum = 0;
  var aaa = arr.forEach(function (element,index,array) {
    console.log(element); // 输出数组中的每一个元素
    console.log(index); // 数组元素对应的索引值
    console.log(array); // 数组本身 [111, 222, 333, 444, 555]
    sum += element; //数组中元素求和;
  });
  console.log(sum); // 数组元素加起来的和
  console.log(aaa);//undefined;没有返回值 所以返回undefined
Copy after login

map ()

// 对数组中每一项运行回调函数,返回该函数的结果组成的新数组
//  return什么新数组中就有什么; 不return返回undefined; 对数组二次加工
例:
  var arr = [111,222,333,444,555];
  var newArr = arr.map(function (element, index, array) {
    if(index == 2){
      return element; // 这里return了 所以下面返回的值是333
    }
    return element*100; // 返回的元素值都乘上100后的值
  })
  console.log(newArr); // [11100, 22200, 333, 44400, 55500]
Copy after login

some()

//对数组中每一项运行回调函数,如果该函数对某一项返回true,则some返回true; 像杀手,有一个成功,就胜利了!!!
例:
  var arr = [111,222,333,444,555];
  var bool = arr.some(function (ele,i,array) {
    //判断:数组中有3的倍数
    if(ele%3 == 0){
      return true;
    }
    return false;
  })
  alert(bool); //true ; 有一个成功就是true
Copy after login

Array clearing

  1. arr.length = 0; // (不好,伪数组无法清空)
  2. arr.splice(0); // 伪数组没有这个方法;
  3. arr = [];   // 可以操作伪数组; (推荐!)
Copy after login
// 伪数组: 就是长的像数组,但是没有数组的方法;也不能添加和删除元素;
例: // arguments
    fn(111,222,333);
    function fn(){
      arguments.length = 0; // 无法清空 返回 [1, 2, 3]
      arguments.splice(0); // 会报错 arguments.splice is not a function
      arguments = []; // 可以清空,返回空数组[] 
      console.log(arguments);
    }
Copy after login

Array case

1. Output a string array in |-divided form, For example, "Liu Bei|Zhang Fei|Guan Yu". Use two methods to implement

    var arr = ["刘备","张飞","关羽"];
    var separator = "|";
    //通过for循环累加
    var str = arr[0];
    for(var i=1;i<arr.length;i++){
      str += separator+arr[i];
    }
    console.log(str); // 刘备|张飞|关羽
    //join()可以把数组中的元素链接成字符串;
    console.log(arr.join("|")); // 刘备|张飞|关羽
Copy after login

2. Reverse the order of the elements of a string array. ["a", "b", "c", "d"] -> [ "d", "c", "b", "a"]. Use two methods to achieve this. Tip: Exchange the i-th and length-i-1

 // 数组.reverse() 方法
      var arr = ["a", "b", "c", "d"];
      console.log(arr.reverse()); // ["d", "c", "b", "a"]
    
    // 三种:1.正向遍历,反向添加; 2.反向遍历,正向添加;  3.元数组元素交换位置;
      for(var i=0;i<arr.length/2;i++){
        var temp = arr[i];
        arr[i] = arr[arr.length-1-i];
        arr[arr.length-1-i] = temp;
      }
      console.log(arr);
Copy after login

3. The salary array [1500, 1200, 2000, 2100, 1800], delete the salary exceeding 2000

  var arr = [1500, 1200, 2000, 2100, 1800];
  //利用filter()形成一个数组;return true;组成的数组;
  var newArr = arr.filter(function (ele, i, array) {
    //2000以上返回false;
    if(ele<2000){
      return true;
    }else{
      return false;
    }
  });
  console.log(newArr); // [1500, 1200, 1800]
Copy after login

4.["c", "a", "z", "a", "x", "a"] Find the position where each a appears in the array

  var arr = ["c", "a", "z", "a", "x", "a"];
  //遍历数组(for/while/do...while)  forEach();
  arr.forEach(function (ele, index, array) {
    //如果元素等于“a”,那么就输出索引值;
    if("a" === ele){
      console.log(index);
    }
  });
Copy after login

5. Write a method Remove duplicate elements from an array (array deduplication)

    var arr = ["鸣人","鸣人","佐助","佐助","小樱","小樱"];
  // 方法1: 思路:定义一个新数组,遍历老数组,判断,如果新数组里面没有老数组的元素就添加,否则就不添加;
    var newArr = [];
    //遍历老数组
    arr.forEach(function (ele,index,array) {
      //检测老数组中的元素,如果新数组中存在就不添加了,不存在才添加;
      if(newArr.indexOf(ele) === -1){//不存在就添加;(去新数组中查找元素索引值,如果为-1就是没有)
        newArr.push(ele);
      }
    });
    console.log(newArr); // ["鸣人", "佐助", "小樱"]
Copy after login

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to use state and setState in react (detailed tutorial)

How to add mobile phone verification in Vue Code component

How to control the global console.log switch in Vue

How to prohibit the bottom page of the pop-up window from following the scroll

How to detect whether the port is occupied in Node.js

How to use the Vue.use() component through the global method

How to use the swiper component in WeChat applet

The above is the detailed content of How to use array functions in JS. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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 use JS and Baidu Maps to implement map pan function How to use JS and Baidu Maps to implement map pan function Nov 21, 2023 am 10:00 AM

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

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

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

How to use JS and Baidu Maps to implement map heat map function How to use JS and Baidu Maps to implement map heat map function Nov 21, 2023 am 09:33 AM

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

How to use JS and Baidu Map to implement map click event processing function How to use JS and Baidu Map to implement map click event processing function Nov 21, 2023 am 11:11 AM

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

How to use JS and Baidu Maps to implement map polygon drawing function How to use JS and Baidu Maps to implement map polygon drawing function Nov 21, 2023 am 10:53 AM

How to use JS and Baidu Maps to implement map polygon drawing function. In modern web development, map applications have become one of the common functions. Drawing polygons on the map can help us mark specific areas for users to view and analyze. This article will introduce how to use JS and Baidu Map API to implement map polygon drawing function, and provide specific code examples. First, we need to introduce Baidu Map API. You can use the following code to import the JavaScript of Baidu Map API in an HTML file

See all articles