网站图片展示源代码长宁集团网站建设
web/
2025/10/8 14:07:49/
文章来源:
网站图片展示源代码,长宁集团网站建设,普象工业设计网站,农业电商网站建设ppES6 为数组新增了一些非常有用的 API#xff0c;这些 API 提高了数组操作的便利性和效率。以下是 ES6 给数组新增的主要 API 及其详细解释和示例#xff1a;
1. Array.from()
Array.from() 方法从类数组对象或可迭代对象创建一个新的数组实例。
const arrayLike {0: a,1:…ES6 为数组新增了一些非常有用的 API这些 API 提高了数组操作的便利性和效率。以下是 ES6 给数组新增的主要 API 及其详细解释和示例
1. Array.from()
Array.from() 方法从类数组对象或可迭代对象创建一个新的数组实例。
const arrayLike {0: a,1: b,2: c,length: 3
};
const arr Array.from(arrayLike);
console.log(arr); // 输出: [a, b, c]const set new Set([a, b, c]);
const arrFromSet Array.from(set);
console.log(arrFromSet); // 输出: [a, b, c]2. Array.of()
Array.of() 方法创建一个具有可变数量参数的新数组实例而不考虑参数的数量或类型。
const arr1 Array.of(1, 2, 3);
console.log(arr1); // 输出: [1, 2, 3]const arr2 Array.of(7);
console.log(arr2); // 输出: [7]3. Array.prototype.find()
find() 方法返回数组中满足提供的测试函数的第一个元素的值。如果没有找到满足条件的元素则返回 undefined。
const array [5, 12, 8, 130, 44];
const found array.find(element element 10);
console.log(found); // 输出: 124. Array.prototype.findIndex()
findIndex() 方法返回数组中满足提供的测试函数的第一个元素的索引。如果没有找到满足条件的元素则返回 -1。
const array [5, 12, 8, 130, 44];
const index array.findIndex(element element 10);
console.log(index); // 输出: 15. Array.prototype.fill()
fill() 方法用一个固定值填充数组中从起始索引到终止索引的全部元素。
const array [1, 2, 3, 4, 5];
array.fill(0, 2, 4);
console.log(array); // 输出: [1, 2, 0, 0, 5]6. Array.prototype.copyWithin()
copyWithin() 方法浅复制数组的一部分到同一数组中的另一个位置并返回它而不修改其大小。
const array [1, 2, 3, 4, 5];
array.copyWithin(0, 3);
console.log(array); // 输出: [4, 5, 3, 4, 5]7. Array.prototype.entries()
entries() 方法返回一个新的数组迭代器对象该对象包含数组中每个索引的键/值对。
const array [a, b, c];
const iterator array.entries();for (const [index, value] of iterator) {console.log(index, value); // 输出: 0 a, 1 b, 2 c
}8. Array.prototype.keys()
keys() 方法返回一个新的数组迭代器对象该对象包含数组中每个索引的键。
const array [a, b, c];
const iterator array.keys();for (const key of iterator) {console.log(key); // 输出: 0, 1, 2
}9. Array.prototype.values()
values() 方法返回一个新的数组迭代器对象该对象包含数组中每个索引的值。
const array [a, b, c];
const iterator array.values();for (const value of iterator) {console.log(value); // 输出: a, b, c
}10. Array.prototype.includes()
includes() 方法用来判断一个数组是否包含一个指定的值如果是返回 true否则返回 false。
const array [1, 2, 3];
console.log(array.includes(2)); // 输出: true
console.log(array.includes(4)); // 输出: false总结
ES6 为数组新增的这些 API 提供了更强大和简洁的操作方式使得数组操作更加方便和直观。通过利用这些新特性开发者可以编写出更加简洁、高效和可读的代码。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/89088.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!