Home Web Front-end JS Tutorial Commonly used traversal methods for javascript arrays (code examples)

Commonly used traversal methods for javascript arrays (code examples)

Oct 26, 2018 pm 04:16 PM
css html html5 javascript node.js

What this article brings to you is about the commonly used traversal methods (code examples) of JavaScript arrays. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Commonly used traversal methods for javascript arrays (code examples)

Preface

This article mainly introduces common array traversal methods: forEach, map, filter, find, every, some, reduce, they all have one thing in common: they will not change the original array.

1. forEach: Traverse the array

var colors = ["red","blue","green"];
// ES5遍历数组方法
for(var i = 0; i <pre class="brush:php;toolbar:false">// ES6 forEach
colors.forEach(function(color){
 console.log(color);//red blue green
});
Copy after login

Let’s look at an example again: traverse the values ​​in the array and calculate the sum

var numbers = [1,2,3,4,5];
var sum = 0;
numbers.forEach(number=>sum+=number)
console.log(sum)//15
Copy after login

2. Map: Map an array into another array

map processes each element of the array through the specified function and returns the new array after processing. Map does not change the original array.

The difference between forEach and map is that forEach has no return value.
map needs to return a value. If no return is given, it will return undefined by default

Usage scenario 1
Assume that there is a numerical array (A), and the values ​​in the A array are doubled in the form B array

var numbers = [1,2,3];
var doubledNumbers = [];
// es5写法
for(var i = 0; i <pre class="brush:php;toolbar:false">// es6 map方法
var doubled = numbers.map(function(number){
   return number * 2;
})
console.log(doubled);//[2,4,6]
Copy after login

Usage scenario 2 Assume there is an object array (A), and store the value of a certain attribute of the object in the A array into the B array

var cars = [
  {model:"Buick",price:"CHEAP"},
  {model:"BMW",price:"expensive"}
];
var prices = cars.map(function(car){
    return car.price;
})
console.log(prices);//["CHEAP", "expensive"]
Copy after login

3. Filter: Find all elements that meet the specified conditions from the array

filter() detects numeric elements and returns an array of all elements that meet the conditions. filter() does not change the original array.

Usage scenario 1: Assume there is an object array (A), get the specified type of object in the array and put it into the B array

var porducts = [
  {name:"cucumber",type:"vegetable"},
  {name:"banana",type:"fruit"},
  {name:"celery",type:"vegetable"},
  {name:"orange",type:"fruit"}
];
// es5写法
var filteredProducts = [];
for(var i = 0; i <pre class="brush:php;toolbar:false">// es6 filter
var filtered2 = porducts.filter(function(product){
  return product.type === "vegetable";
})
console.log(filtered2);
Copy after login

Usage scenario 2: Assume there is An object array (A), filter out objects that do not meet the following conditions
Conditions: The quantity of vegetables is greater than 0, and the price is less than 10

var products = [
  {name:"cucumber",type:"vegetable",quantity:0,price:1},
  {name:"banana",type:"fruit",quantity:10,price:16},
  {name:"celery",type:"vegetable",quantity:30,price:8},
  {name:"orange",type:"fruit",quantity:3,price:6}
];
products = products.filter(function(product){
    return product.type === "vegetable" 
    && product.quantity > 0 
    && product.price <p><strong>Usage scenario 3</strong>: Assume there are two arrays (A,B), based on the id value in A, filter out the data that does not match the B array</p><pre class="brush:php;toolbar:false">var post = {id:4,title:"Javascript"};
var comments = [
   {postId:4,content:"Angular4"},
   {postId:2,content:"Vue.js"},
   {postId:3,content:"Node.js"},
   {postId:4,content:"React.js"},
];
function commentsForPost(post,comments){
   return comments.filter(function(comment){
     return comment.postId === post.id;
   })
}
console.log(commentsForPost(post,comments));//[{postId:4,content:"Angular4"},{postId:4,content:"React.js"}]
Copy after login

4. find: Returns the first element of the array that passes the test (judged within the function) Value

Its parameter is a callback function, and all array members execute the callback function in sequence until the first member whose return value is true is found, and then returns that member. If there are no matching members, undefined is returned.
Usage scenario 1
Assume there is an object array (A), find the object that meets the conditions

 var users = [
  {name:"Jill"},
  {name:"Alex",id:2},
  {name:"Bill"},
  {name:"Alex"}
 ];
// es5方法
 var user;
 for(var i = 0; i <pre class="brush:php;toolbar:false">// es6 find
user = users.find(function(user){
  return user.name === "Alex";
})
console.log(user);// {name:"Alex",id:2}找到后就终止循环
Copy after login

Usage scenario 2: Assume there is an object array (A), according to Specify the conditions of the object to find the objects in the array that meet the conditions

var posts = [
 {id:3,title:"Node.js"},
 {id:1,title:"React.js"}
];
var comment = {postId:1,content:"Hello World!"};
function postForComment(posts,comment){
 return posts.find(function(post){
   return post.id === comment.postId;
 })
}
console.log(postForComment(posts,comment));//{id: 1, title: "React.js"}
Copy after login

5. every&some

every: Whether each element in the array meets the specified conditions

some: Whether there are elements in the array that meet the specified conditions

Usage scenario 1: Calculate whether each computer operating system in the object array is available. If the operating system is greater than 16 bits, it means it is available, otherwise it is not available

//ES5方法
var computers = [
 {name:"Apple",ram:16},
 {name:"IBM",ram:4},
 {name:"Acer",ram:32}
];
var everyComputersCanRunProgram = true;
var someComputersCanRunProgram = false;
for(var i = 0; i <pre class="brush:php;toolbar:false">//ES6 some every 
var every = computers.every(function(computer){
  return computer.ram > 16;
})
console.log(every);//false
var some = computers.some(function(computer){
 return computer.ram > 16;
})
console.log(some);//true
Copy after login

In a nutshell: Every: One true is true; Some: One false is false

##Usage scenario 2: Assume there is a registration page, Determine whether the length of all input content is greater than 0

function Field(value){
  this.value = value;
}
Field.prototype.validate = function(){
  return this.value.length > 0;
}
//ES5方法
var username = new Field("henrywu");
var telephone = new Field("18888888888");
var password = new Field("my_password");
console.log(username.validate());//true
console.log(telephone.validate());//true
console.log(password.validate());//true
//ES6 some every
var fields = [username,telephone,password];
var formIsValid = fields.every(function(field){
 return field.validate();
})
console.log(formIsValid);//true
if(formIsValid){
 // 注册成功
}else{
  // 给用户一个友善的错误提醒
}
Copy after login

6. reduce: combine the array into a value

reduce() method receives a method as an accumulator, in the array Each value of (from left to right) starts to be merged into one value.

Usage scenario 1: Calculate the sum of all values ​​in the array

 var numbers = [10,20,30];
 var sum = 0;
//es5 方法
for(var i = 0; i <pre class="brush:php;toolbar:false">// es6 reduce
var sumValue = numbers.reduce(function(sum2,number2){
  console.log(sum2);//0 10 30 60
  return sum2 + number2;
},0);//sum2初始值为0
console.log(sumValue);
Copy after login

Usage scenario 2: Extract an attribute of the object in the array to another In the array

 var primaryColors = [
   {color:"red"},
   {color:"yellow"},
   {color:"blue"}
 ];
 var colors = primaryColors.reduce(function(previous,primaryColor){
    previous.push(primaryColor.color);
    return previous;
 },[]);
 console.log(colors);//["red", "yellow", "blue"]
Copy after login

Usage scenario 3: Determine whether the brackets in the string are symmetrical

function balancedParens(string){
  return !string.split("").reduce(function(previous,char){
    if(previous <p class="comments-box-content"></p>
Copy after login

The above is the detailed content of Commonly used traversal methods for javascript arrays (code 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 use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

How to write split lines on bootstrap How to write split lines on bootstrap Apr 07, 2025 pm 03:12 PM

There are two ways to create a Bootstrap split line: using the tag, which creates a horizontal split line. Use the CSS border property to create custom style split lines.

What Does H5 Refer To? Exploring the Context What Does H5 Refer To? Exploring the Context Apr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

How to insert pictures on bootstrap How to insert pictures on bootstrap Apr 07, 2025 pm 03:30 PM

There are several ways to insert images in Bootstrap: insert images directly, using the HTML img tag. With the Bootstrap image component, you can provide responsive images and more styles. Set the image size, use the img-fluid class to make the image adaptable. Set the border, using the img-bordered class. Set the rounded corners and use the img-rounded class. Set the shadow, use the shadow class. Resize and position the image, using CSS style. Using the background image, use the background-image CSS property.

How to set up the framework for bootstrap How to set up the framework for bootstrap Apr 07, 2025 pm 03:27 PM

To set up the Bootstrap framework, you need to follow these steps: 1. Reference the Bootstrap file via CDN; 2. Download and host the file on your own server; 3. Include the Bootstrap file in HTML; 4. Compile Sass/Less as needed; 5. Import a custom file (optional). Once setup is complete, you can use Bootstrap's grid systems, components, and styles to create responsive websites and applications.

How to resize bootstrap How to resize bootstrap Apr 07, 2025 pm 03:18 PM

To adjust the size of elements in Bootstrap, you can use the dimension class, which includes: adjusting width: .col-, .w-, .mw-adjust height: .h-, .min-h-, .max-h-

See all articles