JS - includes 方法和 map 方法使用方式

前言

编写前端页面时,经常用到 includes 和 map 这两个方法,在此简单记录一下二者的使用方式。

一、includes 方法

1.说明

(1)在JavaScript中,includes() 是一个数组方法,用于判断数组是否包含特定的元素。它返回一个布尔值,表示数组中是否存在指定的元素。

(2)includes() 方法的语法如下:

array.includes(element)

(3)参数说明: 
其中,array 是要进行判断的数组,element 是要查找的元素。

2.示例代码

(1)判断了数组中是否包含 apple 和 grape 两个元素

const fruits = ['apple', 'banana', 'orange'];
console.log(fruits.includes('apple')); // true
console.log(fruits.includes('grape')); // false

二、map 方法

1.说明

(1)JavaScript中的 map() 方法是一个数组方法,用于对数组中的每个元素进行操作,并返回一个新的数组。它接受一个回调函数作为参数,该回调函数会被应用到数组的每个元素上。

(2)map() 方法的语法如下:

array.map(callback(currentValue[, index[, array]])[, thisArg])

(3)参数说明:
- callback:必需,表示对每个元素进行操作的回调函数。
- currentValue:必需,表示当前正在处理的元素。
- index:可选,表示当前正在处理的元素的索引。
- array:可选,表示调用 map() 方法的数组。
- thisArg:可选,表示回调函数中的 this 值。 

2.示例代码

(1)使用 map 方法将数组中的每个元素转换为大写字母

const arr = ['apple', 'banana', 'orange'];
const newArr = arr.map(item => item.toUpperCase());
console.log(newArr); // ['APPLE', 'BANANA', 'ORANGE']

(2)使用 map 方法将数组中的每个元素乘以 2

const arr = [1, 2, 3, 4, 5];
const newArr = arr.map(item => item * 2);
console.log(newArr); // [2, 4, 6, 8, 10]

(3) 使用 map 方法将对象数组中的每个对象的某个属性提取出来

const arr = [
  { name: 'apple', price: 1.5 },
  { name: 'banana', price: 2 },
  { name: 'orange', price: 1 }
];
const prices = arr.map(item => item.price);
console.log(prices); // [1.5, 2, 1]

(4)使用 map 方法将字符串数组中的每个字符串转换为数字 

const arr = ['1', '2', '3', '4', '5'];
const newArr = arr.map(item => parseInt(item));
console.log(newArr); // [1, 2, 3, 4, 5]

(5)使用 map 方法将数组中的每个元素转换为对象 

const arr = ['apple', 'banana', 'orange'];
const newArr = arr.map(item => ({ name: item }));
console.log(newArr); // [{ name: 'apple' }, { name: 'banana' }, { name: 'orange' }]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值