Home Web Front-end JS Tutorial Common operating techniques for JavaScript arrays

Common operating techniques for JavaScript arrays

Dec 12, 2016 am 11:45 AM

Foreword

I believe everyone is used to common array-related operations in jquery or underscore and other libraries, such as $.isArray, _.some, _.find and other methods. This is nothing more than some additional packaging for array operations in native js.
Here we mainly summarize common APIs for JavaScript array operations. I believe it will be helpful for everyone to solve program problems.

1. Properties
An array in JavaScript is a special object. The index used to represent the offset is a property of the object, and the index may be an integer. However, these numeric indices are converted to string types internally because property names in JavaScript objects must be strings.

2. Operations

1 Determine the array type

var array0 = [];    // 字面量
var array1 = new Array();   // 构造器
// 注意:在IE6/7/8下是不支持Array.isArray方法的
alert(Array.isArray(array0));
// 考虑兼容性,可使用
alert(array1 instanceof Array);
// 或者
alert(Object.prototype.toString.call(array1) === '[object Array]');
Copy after login

2 Arrays and strings

are very simple: to convert from an array to a string, use join; to convert from a string to an array, use split.

// join - 由数组转换为字符串,使用join
console.log(['Hello', 'World'].join(','));    // Hello,World
// split - 由字符串转换为数组,使用split
console.log('Hello World'.split(' '));    // ["Hello", "World"]
Copy after login

3 Find elements

I believe everyone commonly uses the string type indexOf, but few know that the indexOf of an array can also be used to find elements.

// indexOf - 查找元素
console.log(['abc', 'bcd', 'cde'].indexOf('bcd'));  // 1
// 
var objInArray = [
    {
        name: 'king',
        pass: '123'
    },
    {
        name: 'king1',
        pass: '234'
    }
];
console.log(objInArray.indexOf({
    name: 'king',
    pass: '123'
}));    // -1
var elementOfArray = objInArray[0];
console.log(objInArray.indexOf(elementOfArray));    // 0
Copy after login

As can be seen from the above, for arrays containing objects, the indexOf method does not obtain the corresponding search results through in-depth comparison, but only compares the references of the corresponding elements.

4 Array connection

Use concat. Please note that a new array will be generated after using concat.

var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
var array3 = array1.concat(array2); // 实现数组连接之后,会创建出新的数组
console.log(array3);
Copy after login

5 List-like operations


are used to add elements, push and unshift can be used respectively, and pop and shift can be used to remove elements.

// push/pop/shift/unshift
var array = [2, 3, 4, 5];
// 添加到数组尾部
array.push(6);
console.log(array); // [2, 3, 4, 5, 6]
// 添加到数组头部
array.unshift(1);
console.log(array); // [1, 2, 3, 4, 5, 6]
// 移除最后一个元素
var elementOfPop = array.pop();
console.log(elementOfPop);   // 6
console.log(array); // [1, 2, 3, 4, 5]
// 移除第一个元素
var elementOfShift = array.shift();
console.log(elementOfShift);   // 1
console.log(array); // [2, 3, 4, 5]
Copy after login

6 The splice method

has two main uses:
① Add and delete elements from the middle of the array
② Obtain a new array from the original array

Of course, the two uses are combined in one go, in some scenarios Focus on purpose one, and some focus on purpose two.

Add and delete elements from the middle of the array. The splice method adds elements to the array. You need to provide the following parameters
① Starting index (that is, where you want to start adding elements)
② The number of elements to be deleted or the number of elements to be extracted (this parameter is set to 0 when adding elements)
③ The elements you want to add to the array

var nums = [1, 2, 3, 7, 8, 9];
nums.splice(3, 0, 4, 5, 6);
console.log(nums);  // [1, 2, 3, 4, 5, 6, 7, 8, 9] 
// 紧接着做删除操作或者提取新的数组
var newnums = nums.splice(3, 4);
console.log(nums);  // [1, 2, 3, 8, 9]
console.log(newnums);   // [4, 5, 6, 7]
Copy after login

7 Sorting

Mainly introduces the two methods of reverse and sort . Array reversal uses reverse, and the sort method can be used not only for simple sorting, but also for complex sorting.

// 反转数组
var array = [1, 2, 3, 4, 5];
array.reverse();
console.log(array); // [5, 4, 3, 2, 1]
我们先对字符串元素的数组进行排序
var arrayOfNames = ["David", "Mike", "Cynthia", "Clayton", "Bryan", "Raymond"];
arrayOfNames.sort();
console.log(arrayOfNames);  // ["Bryan", "Clayton", "Cynthia", "David", "Mike", "Raymond"]
Copy after login

We sort an array of numeric elements

// 如果数组元素时数字类型,sort()方法的排序结果就不能让人满意了
var nums = [3, 1, 2, 100, 4, 200];
nums.sort();
console.log(nums);  // [1, 100, 2, 200, 3, 4]
Copy after login

The sort method sorts the elements in lexicographic order, so it assumes that the elements are all of string type, so even if the elements are of numeric type, they are considered characters String type. At this time, you can pass in a size comparison function when calling the method. When sorting, the sort() method will compare the sizes of the two elements in the array based on this function to determine the order of the entire array.

var compare = function(num1, num2) {
    return num1 > num2;
};
nums.sort(compare);
console.log(nums);  // [1, 2, 3, 4, 100, 200]
var objInArray = [
    {
        name: 'king',
        pass: '123',
        index: 2
    },
    {
        name: 'king1',
        pass: '234',
        index: 1
    }
];
// 对数组中的对象元素,根据index进行升序
var compare = function(o1, o2) {
    return o1.index > o2.index;
};
objInArray.sort(compare);
console.log(objInArray[0].index < objInArray[1].index); // true
Copy after login

8 The iterator method

mainly includes forEach and every, some and map, and filter
forEach. I believe everyone knows it. Let’s mainly introduce the other four methods.
Every method accepts a function with a return value of Boolean type and uses this function for each element in the array. This method returns true if the function returns true for all elements.

var nums = [2, 4, 6, 8];
// 不生成新数组的迭代器方法
var isEven = function(num) {
    return num % 2 === 0;
};
// 如果都是偶数,才返回true
console.log(nums.every(isEven)); // true
some方法也接受一个返回值为布尔类型的函数,只要有一个元素使得该函数返回true,该方法就返回true。
var isEven = function(num) {
    return num % 2 === 0;
};
var nums1 = [1, 2, 3, 4];
console.log(nums1.some(isEven)); // true
Copy after login

Both methods map and filter can generate new arrays. The new array returned by map is the result of applying a certain function to the original elements. For example:

var up = function(grade) {
    return grade += 5;
}
var grades = [72, 65, 81, 92, 85];
var newGrades = grades.ma
Copy after login

The filter method is very similar to the every method, passing in a function whose return value is a Boolean type. Different from the every() method, when the function is applied to all elements in the array and the result is true, this method does not return true, but returns a new array containing the result of applying the function. Elements.

var isEven = function(num) {
    return num % 2 === 0;
};
var isOdd = function(num) {
    return num % 2 !== 0;
};
var nums = [];
for (var i = 0; i < 20; i++) {
    nums[i] = i + 1;
}
var evens = nums.filter(isEven);
console.log(evens); // [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] 
var odds = nums.filter(isOdd);
console.log(odds);  // [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
Copy after login

3. Summary

There are still some problems in the above methods that are not supported by low-level browsers, and other methods need to be used for compatible implementation.

These are common methods that may not be easy for everyone to think of. You may wish to pay more attention to it.

I hope this article will be helpful to everyone’s JavaScript programming design.


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 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)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

See all articles