Home >Web Front-end >JS Tutorial >Sharing some js methods and skills

Sharing some js methods and skills

小云云
小云云Original
2018-03-02 13:35:211054browse

This article mainly shares some js method techniques with you, hoping to help you.

1. Quickly reorder an array

var arr = [1,2,3,4,5,6,7,8,9,10];
arr.sort(function(){ return Math.random-0.5 }) //无规则排序
arr.sort(function(a,b){ return a-b }) //从小到大
arr.sort(function(a,b){ return b-a }) //从大到小

2. Shorter array rewriting method

// 1.去除数组的重复成员(es6新增)
[...new Set(array)]

For example:

var arr= [2,"12",2,12,1,2,1,6,12,13,6];
arr=[...new Set(arr)];
console.log(arr)  //[2, "12", 12, 1, 6, 13]
//2. indexOf方法去重var arrN=[];for(var i=0;i<arr.length;i++){    if(arrN.indexOf(arr[i])<0){        arrN.push(arr[i])    }}
console.log(arrN) //[2, "12", 12, 1, 6, 13]
// 3.相邻数比较法(原理,先排序,一样大的会排在一起,这样一比较,删除相同的,有个问题就是数组必须是用一类型
否则,这样一个数组[1, 1, 12, "12", 12, 13, 2, 2, 2, 6, 6],用以下方法 ==有7个值,===有5个值)
arr.sort();   for(var i=0;i<arr.length;i++){    if(arr[i]==arr[i+1]){        arr.splice(i,1);        i--;    }    } console.log(arr) //[2, "12", 12, 1, 6, 13]

Related recommendations :

javascript loads and runs js methods in order_javascript skills

Introduction to wow.js method of JS library

Share a collection of commonly used js methods

The above is the detailed content of Sharing some js methods and skills. 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