今天,这个单元主要是衔接Day4,练习并熟悉关于阵列的一些方法,
如比对资料、搜寻资料、删除增加资料等等。
而题目分为5题
此处为题目会用到的资料
const people = [ { name: 'Wes', year: 1988 }, { name: 'Kait', year: 1986 }, { name: 'Irv', year: 1970 }, { name: 'Lux', year: 2015 } ];
const comments = [ { text: 'Love this!', id: 523423 }, { text: 'Super good1', id: 823423 }, { text: 'Super good2', id: 823423 }, { text: 'You are the best', id: 2039842 }, { text: 'Ramen is my fav food ever', id: 123523 }, { text: 'Nice Nice Nice!', id: 542328 } ];
第一题 Array.prototype.some():寻找资料是否有年龄为19岁(含)以上的人
用来检查阵列中有任何一笔符合条件的资料
,有的话返回true
,否则false
通常用于比较两个阵列
const ans1 = people.some(p => { return new Date().getFullYear() - p.year >= 19 }); console.log(ans1); //true
第二题 Array.prototype.every():判断是否全部资料年龄都为19岁(含)以上的人
用来检查阵列中是否全部资料都符合条件
,有的话返回true
,否则false
const ans2 = people.every(p => { return new Date().getFullYear() - p.year >= 19 }); console.log(ans2); // false
第三题 Array.prototype.find():找寻资料中id 为 823423的资料
用来找寻阵列中第一笔符合条件的资料,并返回其资料
,类似filter,但filter会保留所有符合条件的。
如果要每笔都查尽量用filter,而只要找一笔资料就用find
const ans3 = comments.find(comment => { return comment.id === 823423; }); // 我刻意在资料中加一笔id相同的资料,但回传第一笔符合的就停止了 console.log(ans3); // text: {"Super good1", id: 823423}
而find大多会运用在更新一笔特定资料
,如(购物车)如下:
let cart = [ {id: 1,count: 1}, {id: 2,count: 1}, {id: 3,count: 1}, {id: 4,count: 1} ]; const item = cart.find(item => { console.log(item.id); // 到3就停止了,因为已找到目标 return item.id === 3; }); // 将item的count更新为8 item.count = 8; console.log(cart); // 0: {id: 1, count: 1} // 1: {id: 2, count: 1} // 2: {id: 3, count: 8} // 3: {id: 4, count: 1}
第四题 Array.prototype.findIndex():找寻资料中id 为 823423的资料
用来找寻阵列中第一笔符合条件的资料
,并返回其下标
(找编号)
const ans4 = comments.findIndex(comment => { return comment.id === 823423; }); console.log(ans4); // 1
第五题 arrayObject.slice(start,num):删除资料中id 为 823423的资料
arrayObject.splice(start,num)
start:起始位置 num:操作个数
slice, splice差别在于splice会影响原资料,slice不会
splice():可以发现原资料也跟着改变。
ans4为我们上一题获得的值(1) // const ans5 = comments.splice(ans4, 1); // console.log(ans5, comments); // 0: {text: "Super good1", id: 823423} ,[{…}, {…}, {…}, {…}, {…}]
解构,会创建一个新的阵列,指向的就不是原资料的位址
let a = [1, 2, 3, 4] console.log([...a] === a); //false
而如果我们要不影响资料使用splice,可以利用解构达到deep copy
在做删除
// const ans5 = [...comments].splice(ans4, 1); // console.log(ans5, comments); // 0: {text: "Super good1", id: 823423} ,[{…}, {…}, {…}, {…}, {…}, {…}]
slice():可以发现原资料不会改变。
var ans6 = comments.slice(0, ans4); // 从下标为2的资料之后全部删除 var ans7 = comments.slice(ans4 + 1); console.log(ans6, ans7, comments); // 0: {text: "Love this!", id: 523423}, // [{…}, {…}, {…}, {…}] // [{…}, {…}, {…}, {…}, {…}, {…}]
为了不影响原资料,我们也可以利用解构,做deep copy
// var [...arr2] = arr // arr[2] = 5 // console.log(arr) // [1, 2, 5, 4, 5] // console.log(arr2) // [1, 2, 3, 4, 5]
或是利用Object.assign来达到 deep copy
let obj1 = { count: 1 }; // 创建一个新的物件(新的位址)并将obj1的资料放进去 let obj3 = Object.assign({}, obj1); obj3.count = 3; console.log(obj1, obj3); //{count: 1} {count: 3}