ES6 —— 数组常用方法(entries、for...of、fill、find、Array.of、Array.from)

36 篇文章 0 订阅
12 篇文章 1 订阅

目录

1、entries 迭代:获取键值对数组

2、for...of :遍历可迭代对象的元素

3、fill( ) 填充,用于将数组中的所有元素替换为指定的值

4、find( ) :查找满足指定条件的第一个元素,并返回该元素

5、Array.of( ) 文本或者变量转换成数组

6、Array.from( ):将可迭代对象转换成数组,主要是将 JSON 格式转换成数组


1、entries 迭代:获取键值对数组

在 JavaScript 中,Object.entries() 方法用于返回一个给定对象自身可枚举属性的键值对数组。这个方法返回的数组中,每个元素都是一个包含键值对的数组。 

返回一个数组的迭代对象,该对象包含数组的键值对 (key/value)。

迭代对象中数组的索引值作为 key, 数组元素作为 value。

// 定义一个对象
const person = {
  name: 'Alice',
  age: 30,
  job: 'Engineer'
};

// 使用 Object.entries() 方法获取对象的键值对数组
const entries = Object.entries(person);

// 输出键值对数组
console.log(entries);

// 结果
[
  ["name", "Alice"],
  ["age", 30],
  ["job", "Engineer"]
]

使用 Object.entries() 方法可以非常方便地将对象的键值对转换为数组形式,这在需要迭代处理对象属性时非常有用。

例如,我们可以结合 Object.entries() 和数组的 forEach 方法来遍历对象的键值对数组。

const person = {
    'name': '小草莓',
    'age': 18,
    'hobby': ['学习', '睡觉']
};
Object.entries(person).forEach(([key, value]) => {
    console.log(`${key}: ${value}`);
});

// 打印结果
name: 小草莓
age: 18
hobby: 学习,睡觉
const arr = ['111','222','333'];
const entries = Object.entries(arr)
console.log(entries)

// 输出结果
[
  ["0", "111"],
  ["1", "222"],
  ["2", "333"]
]
const arr = ['111','222','333'];
let list = arr.entries();
console.log(list.next().value) // [0, '111']
console.log(list.next().value) // [1, '222']
console.log(list.next().value) // [2, '333']

2、for...of :遍历可迭代对象的元素

for...of 是 JavaScript 中的一种循环语句,用于遍历可迭代对象中的元素。它提供了一种简洁的方式来迭代数组、字符串、Set、Map 等可迭代对象的元素,而不需要手动管理索引或迭代器。

 这种形式比 ES5 的 for 循环要简单而且高效

以下是 for...of 循环的基本语法:

 for (variable of iterable) { // 执行的代码块 }

// 遍历数组
const numbers = [1, 2, 3, 4, 5];
for (let number of numbers) {
  console.log(number); // 1 2 3 4 5
}

// 遍历字符串
const message = "Hello";
for (let char of message) {
  console.log(char); // H e l l o
}

// 遍历 Set
const set = new Set([1, 2, 3]);
for (let item of set) {
  console.log(item); // 1 2 3
}

// 遍历 Map
const map = new Map([
  ['name', 'Alice'],
  ['age', 30],
  ['job', 'Engineer']
]);
for (let entry of map) {
  console.log(entry); // ['name', 'Alice']  ['age', 30] ['job', 'Engineer']
}

for...in 循环出的是对象的 key 值,for...of 循环出的是数组 value 值

推荐在循环对象属性的时候,使用 for...in

推荐在遍历数组元素的时候的时候,使用 for...of

for...of 不能循环普通的对象,需要通过和 Object.keys() 搭配使用

     let arr = ['jie','biao','nine'];
     for(let item of arr){
         console.log(item)
     } 
     // jie biao nine 
        let arr = ['jie','biao','nine'];
        for(let index of arr.keys()){
            console.log(index)
        }
        // 0 1 2
         let arr = ['jie','biao','nine'];
         for(let [index,val] of arr.entries()){
             console.log(index + ':' + val)
         }
         // 0:jie 1:biao 2:nine

3、fill( ) 填充,用于将数组中的所有元素替换为指定的值

是 JavaScript 数组的一个方法,用于将数组中的所有元素替换为指定的值。它会修改原始数组,并返回修改后的数组。

 array.fill(value[, start[, end]])

它接收三个参数:

  • value:填充的值
  • start(可选):指定开始替换的索引位置。默认为 0。
  • end(可选):指定结束替换的索引位置(不包括该位置)。默认为数组的长度。

需要注意的是,结束替换的索引位置是不包括在替换范围内的。 

let arr = [0, 1, 2, 3, 4, 5, 6];
arr.fill("a", 2, 4);
console.log(arr); // [0, 1, 'a', 'a', 4, 5, 6]

const numbers = [1, 2, 3, 4, 5];
console.log(numbers.fill(0));         // [0, 0, 0, 0, 0]

使用 Array(5) 创建了一个长度为 5 的新数组,并使用 fill('Hello') 将所有元素填充为 'Hello'。最终得到一个包含 5 个 'Hello' 的新数组。

const newArray = Array(5).fill('Hello');
console.log(newArray);   // ["Hello", "Hello", "Hello", "Hello", "Hello"]

需要注意的是,fill() 方法会直接修改原始数组,而不是创建一个新的数组副本。如果需要保留原始数组,可以先创建一个副本,然后再使用 fill() 方法。例如:

const originalArray = [1, 2, 3];
const newArray = [...originalArray].fill(0);
console.log(originalArray);   // [1, 2, 3]
console.log(newArray);        // [0, 0, 0]

使用扩展运算符 ... 创建了原始数组的副本 newArray,然后在副本上使用 fill(0) 方法进行修改。这样就保留了原始数组的值,同时得到了一个修改后的新数组。

4、find( ) :查找满足指定条件的第一个元素,并返回该元素

用于查找满足指定条件的第一个元素,并返回该元素,没有则返回 undefined它接收一个回调函数作为参数,该回调函数用于定义查找的条件。 

array.find(callback[, thisArg])

  • callback:用于测试每个元素的回调函数,它接收三个参数:element(当前元素的值),index(当前元素的索引),array(原始数组)。
  • thisArg(可选):执行回调函数时使用的上下文对象。
const arr = [1, 2, 33, 4, 5, 6];
let str = arr.find((value, index, arr) => {
    return value > 2;
})
console.log(str) // 33 

需要注意的是,find() 方法只会返回满足条件的第一个元素,并不会查找所有满足条件的元素。

find() 方法还可以使用第二个参数 thisArg 来指定回调函数执行时的上下文对象。这在需要在回调函数中使用外部变量或者需要绑定特定的 this 上下文时很有用。

const person = {
  name: '小草莓',
  age: 30,
  hobbies: ['学习', '睡觉'],
  checkHobby: function(hobby) {
    return this.hobbies.includes(hobby);
  }
};

// 查找第一个满足 hobby 为 'reading' 的元素
const result = person.hobbies.find(person.checkHobby, person);
console.log(result);   // '学习'

5、Array.of( ) 文本或者变量转换成数组

用于创建一个包含任意数量参数的新数组。它会根据传入的参数创建数组,并返回该数组。

const array1 = Array.of(1, 2, 3, 4, 5);
console.log(array1);   // [1, 2, 3, 4, 5]

const array2 = Array.of('a', 'b', 'c');
console.log(array2);   // ['a', 'b', 'c']

const array3 = Array.of(1, 'two', true);
console.log(array3);   // [1, 'two', true]

需要注意的是,与 Array.of() 方法不同的是,Array() 构造函数在只有一个参数且该参数为数字时,会被解释为创建指定长度的数组,而不是将该数字作为元素添加到数组中。例如:

const array4 = Array(5);
console.log(array4);   // [undefined, undefined, undefined, undefined, undefined]

const array5 = Array(1, 2, 3, 4, 5);
console.log(array5);   // [1, 2, 3, 4, 5]

Array(5) 创建了一个长度为 5 的数组,并用 undefined 填充了所有元素。而 Array(1, 2, 3, 4, 5) 则创建了一个包含参数的新数组。

使用 Array.of() 方法可以避免上述混淆,始终将传入的参数作为数组的元素。

6、Array.from( ):将可迭代对象转换成数组,主要是将 JSON 格式转换成数组

是 JavaScript 的一个静态方法,用于从类数组对象或可迭代对象创建一个新的数组实例。

Array.from() 方法不会改变原始对象,而是返回一个新的数组实例。

它可以将具有 length 属性的对象(比如字符串、类似数组的对象等)或可迭代对象(比如 Set、Map、Array 等)转换为真正的数组。 

Array.from(arrayLike[, mapFn[, thisArg]])

  • arrayLike:要转换为数组的类数组对象或可迭代对象。
  • mapFn(可选):映射函数,用于对每个元素进行处理。
  • thisArg(可选):执行映射函数时使用的 this 值。

将不同类型的对象转换为数组: 字符串、Set、数组

// 将字符串转换为数组
const str = 'Hello';
const array1 = Array.from(str);
console.log(array1);   // ['H', 'e', 'l', 'l', 'o']

// 将 Set 转换为数组
const set = new Set([1, 2, 3]);
const array2 = Array.from(set);
console.log(array2);   // [1, 2, 3]

// 使用映射函数进行处理
const array3 = Array.from([1, 2, 3], (x) => x * 2);
console.log(array3);   // [2, 4, 6]

Array.from() 方法还可以使用第三个参数 thisArg指定执行映射函数时的上下文对象。这在需要在映射函数中使用外部变量或者需要绑定特定的 this 上下文时很有用。

const obj = {
  count: 5,
  increment: function() {
    return Array.from({ length: this.count }, (item, index) => index + 1);
  }
};
console.log(obj.increment());   // [1, 2, 3, 4, 5]

在这个示例中,我们定义了一个 obj 对象,它有一个 increment 方法用于生成一个由 1 到 count 的数字组成的数组。通过在 Array.from() 方法中传递 { length: this.count },我们创建了一个具有指定长度的类数组对象,并使用箭头函数作为映射函数来生成每个元素的值。  

json 在最后必须有一个 length 属性

let json = {
    '0': '111',
    '1': '222',
    '2': '333',
    length: 3  // 一定要加这个属性
}
let arr = Array.from(json)
console.log(arr) // ["111", "222", "333"]
let json = {
    '0': '111',
    '1': '222',
    '2': '333',
}
let arr = Array.from(json)
console.log(arr) // []
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值