javascript中遍歷數(shù)組有哪幾種方法?相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。
在蘭州等地區(qū),都構建了全面的區(qū)域性戰(zhàn)略布局,加強發(fā)展的系統(tǒng)性、市場前瞻性、產(chǎn)品創(chuàng)新能力,以專注、極致的服務理念,為客戶提供網(wǎng)站制作、成都網(wǎng)站設計 網(wǎng)站設計制作定制設計,公司網(wǎng)站建設,企業(yè)網(wǎng)站建設,品牌網(wǎng)站建設,全網(wǎng)整合營銷推廣,成都外貿(mào)網(wǎng)站制作,蘭州網(wǎng)站建設費用合理。
有幾種方法可以遍歷數(shù)組,下面將逐個羅列!
let index = 0;
const array = [1, 2, 3, 4, 5];
while (index < array.length) {
console.log(array[index]);
index++;
}
const array = [1,2,3,4,5];
for(let index=0;index<array.length;index++){
console.log(array[index]);
}
for(let index in array){
console.log(array[index]);
}
const array=[1,2,3,4,5];
array.forEach(function(current_value,index,array){
console.log(`At index ${index} in array ${array} the value is ${current_value}`)
})
最后一個構造很有用,但是不會返回新數(shù)組,這對于你的特定情況可能是不希望的。map通過對每個元素應用一個函數(shù)然后返回新數(shù)組來解決此問題。
const array = [1,2,3,4,5];
const square = x =>Math.pow(x,2);
const squares = array.map(square);
console.log(`${array}`);
console.log(`${squares}`)
reduce()方法對累加器和數(shù)組中的每個元素(從左到右)應用一個函數(shù),以將其減小為單個值
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 arrray:${array} is ${array_sum}`);
根據(jù)布爾函數(shù)過濾篩選數(shù)組中的元素
const array = [1,2,3,4,5];
const even = x => x%2 === 0;
const even_array = array.filter(even);
console.log(`even numbers in array ${array} : ${even_array}`);
得到了一個數(shù)組,想測試每個元素是否滿足給定條件
const array = [1,2,3,4,5,8];
const under_six = x => x<6;
if(array.every(under_six)){
console.log(`every elemnet in the array is less than 6`);
}
else{
console.log(`at least one element in the array was bigger than 6`);
}
測試是否至少有一個元素與布爾函數(shù)匹配
const array = [2,4,5,6,8];
const over_five = x => x>5;
if(array.some(over_five)){
console.log(`at least one element bigger than 5 was found`);
}
else{
console.log(`no element bigger than 5 was found`);
}
到此就結束啦,如果還有其他的歡迎補充!
看完上述內(nèi)容,你們掌握javascript中遍歷數(shù)組有哪幾種方法的方法了嗎?如果還想學到更多技能或想了解更多相關內(nèi)容,歡迎關注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!
本文名稱:javascript中遍歷數(shù)組有哪幾種方法
文章URL:http://www.chinadenli.net/article16/gisdgg.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供外貿(mào)建站、軟件開發(fā)、網(wǎng)站維護、網(wǎng)頁設計公司、企業(yè)網(wǎng)站制作、虛擬主機
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)