Table of Contents
Array.sort()
Array.splice()
Array.toLocaleString()
Array.toSource()
Array.toString()
Array.unshift()
Array.values()
Home Web Front-end JS Tutorial A brief analysis of some operating methods of Array objects in JS (with code)

A brief analysis of some operating methods of Array objects in JS (with code)

Aug 20, 2021 am 11:15 AM
java javascript js

In the previous article "This article explains some operating methods of Object objects in JS (share)", we learned about some operating methods of Object objects in JS. The following article will help you understand some operating methods of Array objects in JS. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

A brief analysis of some operating methods of Array objects in JS (with code)

##javascriptArraySome efficient operation methods

Array.from()

Method creates a new array instance from an array-like or iterable object.

console.log(Array.from("foo"));
// expected output: Array ["f", "o", "o"]
console.log(Array.from([1, 2, 3], (x) => x + x));
// expected output: Array [2, 4, 6]
Copy after login

Array.isArray()

is used to determine whether the passed value is an

Array.

Array.isArray([1, 2, 3]);
// true
Array.isArray({ foo: 123 });
// false
Array.isArray("foobar");
// false
Array.isArray(undefined);
// false
Copy after login

Array.obsolete()

Used to asynchronously monitor changes in the array

has been deprecated Syntax: Array.observe( arr, callback)

Array.of()

method creates a new array instance with a variable number of arguments, regardless of the number or type of arguments.

Array.of(7); // [7]
Array.of(1, 2, 3); // [1, 2, 3]

Array(7); // [ , , , , , , ]
Array(1, 2, 3); // [1, 2, 3]
//es5
if (!Array.of) {
  Array.of = function () {
    return Array.prototype.slice.call(arguments);
  };
}
Copy after login

Array.concat()

The method is used to merge two or more arrays. This method does not change the existing array, but returns a new array.

var array1 = ["a", "b", "c"];
var array2 = ["d", "e", "f"];

console.log(array1.concat(array2));
// expected output: Array ["a", "b", "c", "d", "e", "f"]
Copy after login

Array.copyWithin()

The method shallowly copies a portion of an array to another location in the same array and returns it without modifying its size. The

var array1 = [1, 2, 3, 4, 5];

// place at position 0 the element between position 3 and 4
console.log(array1.copyWithin(0, 3, 4));
// expected output: Array [4, 2, 3, 4, 5]

// place at position 1 the elements after position 3
console.log(array1.copyWithin(1, 3));
// expected output: Array [4, 4, 5, 4, 5]
Copy after login

Array.entries()

method returns a new

Array Iterator object that contains the key/value pairs for each index in the array.

var array1 = ["a", "b", "c"];

var iterator1 = array1.entries();

console.log(iterator1.next().value);
// expected output: Array [0, "a"]

console.log(iterator1.next().value);
// expected output: Array [1, "b"]
Copy after login

Array.every()

The method tests whether all elements of the array pass the test of the specified function.

var array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every((x) => x < 40));
//out true
Copy after login

Array.fill()

The method fills all elements in an array from the starting index to the ending index with a fixed value. Excluding termination

var array1 = [1, 2, 3, 4];
// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]
// fill with 5 from position 1
console.log(array1.fill(5, 1));
// expected output: [1, 5, 5, 5]
console.log(array1.fill(6));
// expected output: [6, 6, 6, 6]
Copy after login

Array.filter()

The method creates a new array containing all elements of the test implemented by the provided function.

var words = ["spray", "limit", "elite", "exuberant", "destruction", "present"];

const result = words.filter((word) => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
Copy after login

Array.find()

The method returns the value of the first element in the array that satisfies the provided test function. Otherwise

undefined is returned.

var array1 = [5, 12, 8, 130, 44];

var found = array1.find((x) => x > 10);

console.log(found);
// expected output: 12
Copy after login

Array.findIndex()

The method returns the index of the first element in the array that satisfies the provided test function. Otherwise return

-1.

var array1 = [5, 12, 8, 130, 44];

var index = array1.findIndex((x) => x > 10);

console.log(index);
// expected output: 1
Copy after login

Array.flat()

The method will recurse to the specified depth to connect all sub-arrays and return a new array.

var arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]

var arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

var arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]
var arr4 = [1, 2, , 4, 5];
arr4.flat();
// [1, 2, 4, 5]
Copy after login

Array.flatMap()

The method first maps each element using a mapping function and then compresses the result into a new array. It's almost identical to

flat with map and depth value 1, but flatMap is usually slightly more efficient when combined into one method.

var arr1 = [1, 2, 3, 4];

arr1.map((x) => [x * 2]);
// [[2], [4], [6], [8]]

arr1.flatMap((x) => [x * 2]);
// [2, 4, 6, 8]

// only one level is flattened
arr1.flatMap((x) => [[x * 2]]);
// [[2], [4], [6], [8]]
Copy after login

Array.forEach()

The method executes the provided function once for each element of the array.

var array1 = ["a", "b", "c"];

array1.forEach((value, index, arr) => console.log(value));
// output &#39;a&#39;
// output &#39;b&#39;
// output &#39;c&#39;
Copy after login

Array.includes(value,index)

method is used to determine whether an array contains a specified value. Depending on the situation, if it does, it will return

true, otherwise Return false.

var array1 = [1, 2, 3];

console.log(array1.includes(2));
// expected output: true

var pets = ["cat", "dog", "bat"];

console.log(pets.includes("cat"));
// expected output: true

console.log(pets.includes("at"));
// expected output: false
Copy after login

Array.indexOf()

The method returns the first index where a given element can be found in the array, or

-1 if it does not exist.

/var beasts = [&#39;ant&#39;, &#39;bison&#39;, &#39;camel&#39;, &#39;duck&#39;, &#39;bison&#39;];

console.log(beasts.indexOf(&#39;bison&#39;));
// expected output: 1

// start from index 2
console.log(beasts.indexOf(&#39;bison&#39;, 2));
// expected output: 4

console.log(beasts.indexOf(&#39;giraffe&#39;));
// expected output: -1
Copy after login

Array.join()

The method joins all elements of an array (or an array-like object) into a string and returns this character

var elements = ["Fire", "Wind", "Rain"];

console.log(elements.join());
// expected output: Fire,Wind,Rain

console.log(elements.join(""));
// expected output: FireWindRain

console.log(elements.join("-"));
// expected output: Fire-Wind-Rain

//数组[1,2,3,3,4,5]求和
eval([1, 2, 3, 3, 4, 5].join("+")) = 18;
Copy after login

Array. The keys()

method returns a new

Array iterator containing the keys for each index in the array.

var array1 = ["a", "b", "c"];
var iterator = array1.keys();

for (let key of iterator) {
  console.log(key); // expected output: 0 1 2
}
Copy after login

Array.lastIndexOf(item, index)

method returns the index of the last element in the array (that is, a valid

JavaScript value or variable), If it does not exist, -1 is returned. Search forward from the back of the array, starting from fromIndex.

var animals = ["Dodo", "Tiger", "Penguin", "Dodo"];

console.log(animals.lastIndexOf("Dodo"));
// expected output: 3

console.log(animals.lastIndexOf("Tiger"));
// expected output: 1
Copy after login

Array.map()

The method creates a new array whose result is the result of calling a provided function on each element in the array.

var array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map((x) => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]
Copy after login

Array.pop()

The method removes the last element from the array and returns the value of the element. This method changes the length of the array.

var plants = ["broccoli", "cauliflower", "cabbage", "kale", "tomato"];
console.log(plants.pop());
// expected output: "tomato"
console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]
plants.pop();
console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage"]
Copy after login

Array.push()

The method adds one or more elements to the end of the array and returns the length of the new array.

var animals = ["pigs", "goats", "sheep"];

console.log(animals.push("cows"));
// expected output: 4

console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows"]

animals.push("chickens");

console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows", "chickens"]
Copy after login

Array.reduce()

The method applies a function to the accumulator and each element in the array (from left to right), reducing it to a single value.

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15
Copy after login

Array.reduceRight()

The method accepts a function as an accumulator (

accumulator) and each value of the array (from right to left) reduces it to single value.

const array1 = [
  [0, 1],
  [2, 3],
  [4, 5],
].reduceRight((accumulator, currentValue) => accumulator.concat(currentValue));

console.log(array1);
// expected output: Array [4, 5, 2, 3, 0, 1]
Copy after login

Array.reverse()

The method reverses the position of the elements in the array.

var array1 = ["one", "two", "three"];
console.log("array1: ", array1);
// expected output: Array [&#39;one&#39;, &#39;two&#39;, &#39;three&#39;]

var reversed = array1.reverse();
console.log("reversed: ", reversed);
// expected output: Array [&#39;three&#39;, &#39;two&#39;, &#39;one&#39;]

/* Careful: reverse is destructive. It also changes
the original array */

console.log("array1: ", array1);
// expected output: Array [&#39;three&#39;, &#39;two&#39;, &#39;one&#39;]
Copy after login

Array.shift()

The method removes the first element from the array and returns the value of the element. This method changes the length of the array.

var array1 = [1, 2, 3];

var firstElement = array1.shift();

console.log(array1);
// expected output: Array [2, 3]

console.log(firstElement);
// expected output: 1
Copy after login

Array.slice()

The method returns a shallow copy of a portion of the selected array from start to end (excluding the end) to a new array object. And the original array will not be modified.

var animals = ["ant", "bison", "camel", "duck", "elephant"];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]
Copy after login

Array.some()

The method tests whether some elements in the array pass a test implemented by the provided function.

var array = [1, 2, 3, 4, 5];

var even = function (element) {
  // checks whether an element is even
  return element % 2 === 0;
};

console.log(array.some(even));
// expected output: true
Copy after login

Array.sort()

方法用原地算法对数组的元素进行排序,并返回数组。排序不一定是稳定的。默认排序顺序是根据字符串Unicode码点。

var months = ["March", "Jan", "Feb", "Dec"];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]

var array1 = [1, 30, 4, 21];
array1.sort();
console.log(array1);
// expected output: Array [1, 21, 30, 4]
Copy after login

Array.splice()

方法通过删除现有元素和/或添加新元素来更改一个数组的内容。

var months = ["Jan", "March", "April", "June"];
months.splice(1, 0, "Feb");
// 增
console.log(months);
// expected output: Array [&#39;Jan&#39;, &#39;Feb&#39;, &#39;March&#39;, &#39;April&#39;, &#39;June&#39;]

months.splice(4, 1, "May");
// 改
console.log(months);
// expected output: Array [&#39;Jan&#39;, &#39;Feb&#39;, &#39;March&#39;, &#39;April&#39;, &#39;May&#39;]
// 删
months.splice(4, 1);
console.log(months);
//output: ["Jan", "Feb", "March", "April"]
Copy after login

Array.toLocaleString()

返回一个字符串表示数组中的元素。数组中的元素将使用各自的toLocaleString方法转成字符串,这些字符串将使用一个特定语言环境的字符串(例如一个逗号 ",")隔开。

var array1 = [1, "a", new Date("21 Dec 1997 14:12:00 UTC")];
var localeString = array1.toLocaleString("en", { timeZone: "UTC" });

console.log(localeString);
// expected output: "1,a,12/21/1997, 2:12:00 PM",
// This assumes "en" locale and UTC timezone - your results may vary
var prices = ["¥7", 500, 8123, 12];
prices.toLocaleString("ja-JP", { style: "currency", currency: "JPY" });

// "¥7,¥500,¥8,123,¥12"
Copy after login

Array.toSource()

返回一个字符串,代表该数组的源代码。

该特性是非标准的,请尽量不要在生产环境中使用它!

var alpha = new Array("a", "b", "c");

alpha.toSource(); //返回["a", "b", "c"]
Copy after login

Array.toString()

返回一个字符串,表示指定的数组及其元素。

var array1 = [1, 2, "a", "1a"];

console.log(array1.toString());
// expected output: "1,2,a,1a"
Copy after login

Array.unshift()

方法将一个或多个元素添加到数组的开头,并返回新数组的长度。

var array1 = [1, 2, 3];

console.log(array1.unshift(4, 5));
// expected output: 5

console.log(array1);
// expected output: Array [4, 5, 1, 2, 3]
Copy after login

Array.values()

方法返回一个新的Array Iterator对象,该对象包含数组每个索引的值。

const array1 = ["a", "b", "c"];
const iterator = array1.values();

for (const value of iterator) {
  console.log(value);
  // expected output: "a" "b" "c"
}
Copy after login

推荐学习:JavaScript视频教程

The above is the detailed content of A brief analysis of some operating methods of Array objects in JS (with code). 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)

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

See all articles