Home Web Front-end JS Tutorial Summary of six JS array usage examples

Summary of six JS array usage examples

Jul 20, 2018 pm 03:20 PM
js array

In the process of learning js, it is necessary to master the methods of js arrays. Here I have summarized the commonly used methods in js arrays, so that everyone can learn from each other. Without further ado, let’s go directly to the main text.

1. Methods inherited by js objects

Array is a special object that inherits the toString() and toLocaleString() of the object Object ) and valueOf() method

1.toString()

toString method returns a symbol-delimited string concatenated by the string form of each value in the array. The string is the same as the string returned by join() without parameters

[1,2,3].toString()//'1,2,3'
['a','b','c'].toString()//'a,b,c'
[1,[2,3]].toString()//'1,2,3'
Copy after login

2.toLocaleString()

toLocaleString() is the localization of toString() Version, under normal conditions, is the same as toString() returns. When the number reaches more than 3 digits, it is automatically formatted and the date can also be formatted

var a = 3333; a.toLocaleString()//3,333
var b = new Date; b.toLocaleString()//2018/7/13 下午3:43:39
Copy after login

3.valueOf()

valueOf() returns itself when dealing with an array object

var a = [1,2,3]; a.valueOf()//[1,2,3];
a.valueOf() instanceOf() Array//true
Copy after login

2. js array conversion method

1.join()

Array.join() is the reverse operation of Array.split(). The former is to merge the arrays into a string in parameter units (default is comma), and the latter is Cut the string into an array. Supports arrays and class arrays, but does not support objects

var a = [1,2,3,4,5]; a.join()//'1,2,3,4,5'
var b = [1,undefined,2,null,3]; b.join()//'1,,2,,3'
var c = Array.prototype; c.join.call('hello','-')//'h-e-l-l-o'
var d = {1:'a',2:'b',length:3}; d.join()//'a,b'
var e = {1:'a',2:'b'}; e.join()//''
Copy after login

3. js array data structure operation method

The data structure of the array is divided into a stack structure (Last in, last out) and queue structure (first in, first out)

Stack structure (last in, last out):

1.push()

push() adds any number of parameters to the end one by one, changes the original array, modifies the array length and returns

var a = [1,2]; a.push('11,22') - a//3 - [1,2,33,44]
var b = [3,4]; a.push([33.44]) - a//2 - [1,2,[33,44]]
Array.prototype.push.apply(a,b)//[1,2,3,4]
Array.prototype.push.call(a,b)//[1,2,[3,4]]
Copy after login

push() can also add parameters to the object. After adding, the object will become an array object. The key of the newly added element corresponds to the index of the array, and the object has a length attribute

var c = {}; Array.prototype.push.call(c,1) //{0:1,length:1}

##2.pop()

pop() removes the last item in the array and returns Array length, and then modify the array length to change the original array

var a = [1,2,3]; a.pop() - a//3 - [1,2];
//如果数组本身是空数组,则返回undefined
var b = []; b.pop()//undefined
Copy after login

Queue structure (forward, first out):

1.shift()

shift() removes the first item in the array, returns the removed element, and then modifies the length of the array to change the array

var a = [1,2,3]; a.shift() - a//1 - [2,3];
Copy after login

2.unshift()

unshift() adds any parameter to the starting position of the array to modify the array length, and returns the array length to change the array

var a = [1,2,3]; a.unshift(4,5) - a//5 - [1,2,3,4,5]
Copy after login

4. JS array sorting method

1.reverse()

reverse() is used to reverse the order of the array, modify the original array, and return the current array

 var a = [1,2,4,3,5]; a.reverse()// [5,3,4,2,1];
Copy after login

2.sort()

sort() changes the array to ascending order by default. sort will call toString() for each array item by default

var a = [1,2,3,4,5]; a.sort() //[1,2,3,4,5]
var b = [1,2,12,13]; c.sort() //[1,12,13,2]
var c = [1,2,'1a','2b']; c.sort() //[1,'1a',2,'2b'];
Copy after login

if the array contains undefined, then undefined will be sorted to the end

var d = [1,3,undefined,2]; d.sort() //[1,2,3,undefined]
Copy after login

If sort has parameters (the parameter must be a function); if the value of the function return is a positive number or the first parameter minus the second parameter, then it is Positive order, otherwise reverse order. If the string is present, it will be minimal. Put it in the starting position in order

function sortNumber(a,b){
  return b-a
}
var e = [1,2,3]; e.sort(sortNumber)//[3,2,1]; 
var f = ['1a',1,'2b',2,3]; f.sort()//['1a','2b',3,2,1];
Copy after login

If the sort parameter is a random positive and negative number returned by the function, the array book order will be random

function sortRandom(a,b){
  return Math.random()-0.5
}
var g = [1,2,3,4,5]; g.sort(sortRandom)//[2,1,5,4,3](此为随机顺序)
Copy after login

3.concat()

The concat() method creates a new array based on the current array and puts the received parameters at the end without affecting the original array

var a = [1,2]; b = [3,4]; a.concat - a//[1,2,3,4] - [1,2];五.创建子数组方法
Copy after login

4.slice()

The slice() method intercepts the starting position of the first parameter and the ending digit of the second parameter. and create a new array. If there are no parameters, it will intercept all

var a = [1,2,3,4,5];a.slice(2,4)//[3,4,5]
var a = [1,2,3,4,5];a.slice(2)//[3,4,5]
var a = [1,2,3,4,5];a.slice(-3)//[3,4,5] 
var a = [3,4,5];a.slice()//[3,4,5]
Copy after login

5.js array deletion method

1.splice()

splice() receives three parameters. The first parameter is required for the position. The second parameter is required for the number to be deleted. If there is only one parameter, all arrays and the second parameter will be deleted. From now on, new items will be optional. What is returned is the deleted array

var a = [1,2,3]; a.splice(2,0,1)-a//[]-[1,2,1,3];
var b = [1,2,3]; a.splice(2,1,1)-a//[3]-[1,2,1];
var c = [1,2,3]; a.splice(2)-a//[1,2,3]-[]
var d = [1,2,3]; a.splice(2,1,4,5)-a//[3]-[1,2,4,5]
Copy after login

2.indexOf()

indexOf() returns the position where the first parameter first appears. When there is a second When parameter n appears, what is returned is that the elements before the nth element are not counted for the first time.

var a = ['a','b','c',a,2,3]; a.indexOf('a')//0
var a = ['a','b','c',a,2,3]; a.indexOf('a',1)//4
var a = ['a','b','c',1,2,3]; a.indexOf('a',-5)//0
Copy after login

3.lastIndexOf()

lastIndexOf( ) is different from indexOf(): search from right to left

var a = ['a','b','c',a,2,3]; a.indexOf('a')//4
var a = ['a','b','c',a,2,3]; a.indexOf('a',1)//0
var a = ['a','b','c',a,2,3]; a.indexOf('a',-1)//0
Copy after login

6.js array merging method

1 The first parameter of the .reduce()

reduce() method is to loop through the specified function array and combine it in a custom form to generate a single value. It receives four parameters (initial variable, current variable, current index, original array object). The second parameter of reduce specifies an initial value to be entered.

var a = [1,2,3,4,5];
a.reduce(function(x,y){return x+y}) // 15
a.reduce(function(x,y){return x+y},3)//18
Copy after login

2.reduceRight()

reduceRight() is different from reduce() in that the index value is from high to low

a.reduce(function(x,y){console.log(x,y);return x+y},0)
// 5,4 9,3 12,2 14,1 15,0
Copy after login

Seven.js array iteration method

##1.map()

map() specifies the operation for each item in the function array function and returns the result of each function call into an array

var a = [1,2,3]; a.map(function(item,index,arr){return item*2})
//[2,4,6]
var b = ['aa','bb','cc'];
a.map(function(item,index,b){return this[item]})
//['aa','bb','cc'];
Copy after login

map()日常中多用于去解析对象中的属性

var c = {[name:1,value:2],[name:11,value:22]}
c.map(function(item){return item.name})//[1,11]
Copy after login

2.forEach()

forEach()给函数数组的每一项运行指定的函数(于map()对比不同于没有返回值)。forEach()可接受第二参数,用来改变this的指向。

var a = {
    name:'111',
    arr:[1,2,3],
    value:function(){
        console.log(this);
        this.arr.forEach(function(){
        console.log(this);
        })
    }
}//循环外this指向value方法,循环内指向a对象
var b = {
  name:'111',
  arr:[1,2,3],
  value:function(){
    console.log(this);
    this.arr.forEach(function(){
      console.log(this);
    },this)
  }
}//全文的this全部都指向对象a
Copy after login

3.filter()

filter()给函数数组的每一项运行指定的函数,并返回制定规则返回True的项的数组。该方法多用于查询,第二个参数值指定this指向

var a = [1,2,3];a.filter(function(item){return item>1)//[2,3];
Copy after login

4.some()

filter()给函数数组的每一项运行指定的函数进行筛选,如果都返回false,则返回false。反之则返回true

a = [1,2,3,4,5];
a.some(function(item){return item === 3;})//true
a.some(function(item){return item === 6;})//false
Copy after login

5.every()

every()给函数数组的每一项运行指定的函数进行筛选,如果有返回false,则返回false。反之如果全部返回true,则返回true;空数组会返回true

a = [1,2,3,4,5];
a.every(function(item){return item === 3;})//false
a.every(function(item){return item < 6;})//true
Copy after login

相关推荐:

JS中数组重排序方法

js数组方法

The above is the detailed content of Summary of six JS array usage examples. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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 remove elements from es6 array How to remove elements from es6 array Jan 11, 2023 pm 03:51 PM

Method: 1. Use shift() to delete the first element, the syntax is "array.shift()"; 2. Use pop() to delete the last element, the syntax is "array.pop()"; 3. Use splice() to delete Elements at any position, the syntax is "array.splice(position, number)"; 4. Use length to delete the last N elements, the syntax is "array.length=original array length-N"; 5. Directly assign the empty array "[ ]" to clear the element; 6. Use delete to delete an element at the specified subscript.

How to convert string to array in javascript How to convert string to array in javascript Nov 23, 2022 pm 07:28 PM

3 conversion methods: 1. Use split() to split a given string into a string array, the syntax is "str.split (separator, maximum length of array)"; 2. Use the expansion operator "... ", iterable string object, convert it into a character array, the syntax "[...str]"; 3. Use Array.from() to convert the string into an array, the syntax "Array.from(str) ".

Can js array be converted into php array? Can js array be converted into php array? Jun 02, 2023 am 10:06 AM

The js array can be converted into a php array. The operation method is: 1. Create a php sample file; 2. Use the syntax "JSON.stringify()" to convert the js array into a string in JSON format; 3. Use the syntax "json_decode()" "Convert the JSON format string to a PHP array. The parameter true is added here, which means that the JSON format string is converted into a PHP associative array.

How to get the length of an array in js How to get the length of an array in js Jun 20, 2023 pm 05:33 PM

Getting the length of an array in JS is very simple. Each array has a length property, which returns the maximum length of the array, that is, its value is equal to the maximum subscript value plus 1. Since numeric subscripts must be less than 2^32-1, the maximum value of the length attribute is equal to 2^32-1. The following code defines an empty array, and then assigns a value to the element with the index equal to 100, then the length property returns 101. Therefore, the length attribute cannot reflect the actual number of array elements.

There are several ways to delete an element from a js array There are several ways to delete an element from a js array Aug 02, 2023 am 10:09 AM

There are 4 ways to delete an element from a js array, namely: 1. Use splice; 2. Use filter; 3. Use the pop method and shift; 4. Use the delete keyword.

JS array sorting: how to use the sort() method JS array sorting: how to use the sort() method Dec 27, 2023 pm 03:40 PM

JavaScript's Array.prototype.sort() method is used to sort the elements of an array. This method sorts in place, that is, it modifies the original array rather than returning a new sorted array. By default, the sort() method sorts strings according to their Unicode code point values. This means that it is used primarily for sorting strings and numbers, rather than for sorting objects or other complex data types.

What are the methods to remove duplicates from js arrays? What are the methods to remove duplicates from js arrays? Aug 09, 2023 pm 04:47 PM

Methods to deduplicate js arrays include using Set, using indexOf, using includes, using filter and using reduce. 1. Use Set, which is characterized by the fact that the elements in the set will not be repeated; 2. Use indexOf to return the first index position of the specified element in the array; 3. Use includes to determine whether an element already exists in the array. 4. Use filter to filter elements; 5. Use reduce to compress elements in an array, etc.

How to find the length and sum of elements of an array in JavaScript How to find the length and sum of elements of an array in JavaScript Sep 20, 2022 pm 02:11 PM

In JavaScript, you can use the length attribute to get the length of the array, the syntax is "array object.length"; you can use the reduce() or reduceRight() function to find the sum of elements, the syntax is "arr.reduce(function f(pre,curr){ return pre+cur})" or "arr.reduceRight(function f(pre,curr){return pre+cur})".

See all articles