返回?cái)?shù)組的最后一個(gè)元素,可以使用pop()函數(shù)
let arr = [1, 3, 4];
console.log(arr.pop());//結(jié)果:4
刪除數(shù)組的第一個(gè)元素,使用shift()函數(shù)
let arr = [1, 3, 4];
arr.shift();
console.log(arr);//結(jié)果:[3萝招, 4]
找出兩個(gè)數(shù)組中的相同元素,可以使用includes函數(shù),返回值為true或者false
let arr1 = [1, 2, 3, 4, 5, 6, 7, 8];
let arr2 = [3, 4, 5, 6];
let arr = [];
for (let item of arr2) {
if (arr1.includes(item)) {
arr.push(item);
}
}
console.log(arr);
將數(shù)字轉(zhuǎn)換為字母,可以使用String.fromCharCode(num)函數(shù)
filter(checkFunction)函數(shù):創(chuàng)建一個(gè)新的數(shù)組奕塑,新數(shù)組中的元素是通過(guò)檢查指定數(shù)組中符合條件的所有元素
function isEven(element) {
return element % 2 === 0;
}
let arr = [1, 2, 3, 4, 5, 6]
let arr1 = arr.filter(isEven);
console.log(arr1);//找出數(shù)組中的偶數(shù)
刪除數(shù)組中的重復(fù)元素
let arr = [1, 1, 2, 2, 4, 5, 6];
let noRepeat = [];
for (let item of arr) {
if (noRepeat.includes(item)){
}else {
noRepeat.push(item);
}
}
console.log(noRepeat);//運(yùn)行結(jié)果:[1, 2, 4, 5, 6];
注意:這里只是刪除了重復(fù)的元素械姻,且保留了重復(fù)出現(xiàn)的元素,并不是徹底刪除重復(fù)出現(xiàn)的元素恩脂。
雙for循環(huán)的抽取
當(dāng)需要兩次for循環(huán)時(shí)帽氓,如下:
for () {
for() {
//執(zhí)行代碼;
}
}
此時(shí)俩块,第二個(gè)for循環(huán)可以抽取為函數(shù)黎休,提高代碼的可讀性和重用性,如下:
for () {
if(function) {
//執(zhí)行代碼;
}
}
注意:function中所帶的參數(shù)個(gè)數(shù)和類(lèi)型根據(jù)實(shí)際情況而定玉凯,且該函數(shù)的返回值類(lèi)型必須是Boolean(true or false)势腮。
二維數(shù)變一維數(shù)組,可以使用flatten()函數(shù)展開(kāi);也可以用后面說(shuō)到的reduce函數(shù)
var ans = flatten([[1, 2], [3, 4]], false, false, 1);
console.log(ans); // => [3, 4]
注意:該函數(shù)在谷歌瀏覽器中調(diào)試時(shí)會(huì)出現(xiàn)錯(cuò)誤漫仆,我在開(kāi)發(fā)者網(wǎng)絡(luò)MDN中也未找到該函數(shù)捎拯。出現(xiàn)的錯(cuò)誤如下:
這里是我搜索到的具體的flatten函數(shù)的用法:http://web.jobbole.com/86404/。
map() 函數(shù)創(chuàng)建一個(gè)新數(shù)組盲厌,其結(jié)果是該數(shù)組中的每個(gè)元素都調(diào)用一個(gè)提供的函數(shù)后返回的結(jié)果署照。
let numbers = [1, 5, 10, 15];
let doubles = numbers.map((x) => {
return x * 2;
});//給數(shù)組中每個(gè)元素乘以2
// doubles is now [2, 10, 20, 30]
// numbers is still [1, 5, 10, 15]
let numbers = [1, 4, 9];
let roots = numbers.map(Math.sqrt);//求數(shù)組元素的開(kāi)方
// roots is now [1, 2, 3]
// numbers is still [1, 4, 9]
求數(shù)組中所有元素的累加,使用reduce函數(shù)
var total = [0, 1, 2, 3].reduce(function(sum, value) {
return sum + value;
}, 0);
注意:reduce函數(shù)也可以實(shí)現(xiàn)二維數(shù)組變一維數(shù)組狸眼,如下:
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
function(a, b) {
return a.concat(b);
},[]);
對(duì)象的訪問(wèn):可以采用'.'或者'[]'
let obj = {};
obj = {
name: 'sara',
age: 19;
}
obj.name; //'sara'
obj['age'];//19
小結(jié):
這些有關(guān)數(shù)組和對(duì)象的使用都可以在[開(kāi)發(fā)者網(wǎng)絡(luò)](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript)中找到藤树,大家也可以通過(guò)該網(wǎng)站學(xué)習(xí)JavaScript的相關(guān)知識(shí)。
這僅僅是我通過(guò)做任務(wù)和看別人的代碼所做出的一些小總結(jié)拓萌,希望大家隨意指正岁钓。