亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

js數組遍歷-Looping over arrays

標簽:
JavaScript

jstips Looping over arrays

JS语言中有很多遍历数组的方法。我们从几个较为传统的遍历方式开始,逐步向大家展示标准的遍历方法。

while
let index = 0;
const array = [1, 2, 3, 4, ,5];

while (index < array.length) {
    console.log(array[index]);
    index++;
}
for(最传统的形式)
const array = [1, 2, 3, 4, 5];
for (let i = 0; i < array.length; i ++) {
    console.log(array[i]);
}
forEach
const array = [1, 2, 3, 4, 5];

array.forEach((current_value, index, arr) => {
    console.log(current_value, index);
});
map

forEach这中方法,并不返回一个新的数组。map函数对数组的每个元素上应用一个函数,并返回一个全新的数组。map是immutable的,更加的安全。

//.map(current_value, index, array)
const array = [1, 2, 3, 4, 5];
const square = x => Math.pow(x, 2);
const squares = array.map(square);
console.log(`Original array: ${array}`);
console.log(`Squared array: ${squares}`);
reduce

reduce函数对数组的每个元素执行累加器,最后返回一个值。

const array = [1, 2, 3, 4, 5];
const sum = (x, y) => x + y;
const array_sum = array.reduce(sum, 0);
console.log(`The sum of array: ${array} is ${array_sum}`);
filter

对一个数组实施过滤

const array = [1, 2, 3, 4, 5];
const event = x => x % 2 === 0;
const event_arr = array.filter(event);
console.log(event_arr);
every

判断一个数组上的元素是否全部符合某种条件

const array = [1, 2, 3, 4, 5, 6];
const under_seven = x => x < 7;

if (array.every(under_seven)) {
  console.log('Every element in the array is less than 7');
} else {
  console.log('At least one element in the array was bigger than 7');
}
some

判断一个数组上的元素是否至少有一个符合某种条件

const array = [1,2,3,9,5,6,4];
const over_seven = x => x > 7;

if (array.some(over_seven)) {
  console.log('At least one element bigger than 7 was found');
} else {
  console.log('No element bigger than 7 was found');
}

from: xixi小站

點擊查看更多內容
2人點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
Web前端工程師
手記
粉絲
120
獲贊與收藏
651

關注作者,訂閱最新文章

閱讀免費教程

感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消