1.07-Array Cardio2:
* 這幾天有乖乖寫有差,可能也是這篇比較容易的關係,漸漸上手了。希望30天後有所不同。
* 重點: some(), all(), find(), findIndex()
* 刪除方法 - splice(), 新建一個Array+ ...slice()
// ## Array Cardio Day 2
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 good', id: 823423 },
{ text: 'You are the best', id: 2039842 },
{ text: 'Ramen in my fav food ever', id: 123523 },
{ text: 'Nice Nice Nice!', id: 542328 }
];
// Some and Every Checks
// Array.prototype.some() // is at least one person 19?
const isAdult = people.some(function(person){
const CurrentYear = (new Date()).getFullYear();
if(CurrentYear - person.year >= 19 ){
return true
}
})
//DRY
const isAdult2 = people.some(person => {
const CurrentYear = (new Date()).getFullYear();
return CurrentYear - person.year >= 19;
})
// Array.prototype.every() // is everyone 19?
const allAdult = people.every(person =>{
const CurrentYear = (new Date()).getFullYear();
return CurrentYear - person.year >= 19;
})
console.log(allAdult);
// Array.prototype.find()
// Find is like filter, but instead returns just the one you are looking for
// find the comment with the ID of 823423
const commentID = comments.find(comment => comment.id === 823423)
console.log({commentID});
// Array.prototype.findIndex()
// Find the comment with this ID
// delete the comment with the ID of 823423
const Index = comments.findIndex(comment => comment.id === 823423); //1 => second one
//use splice
comments.splice(Index, 1);
//or
const newComments = [
...comments.slice(0, Index),
...
comments.slice(Index +1)
]
console.log(newComments);
2.08-Fun with HTML5 Canvas:
//setting
const canvas = document.getElementById('draw');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx.strokeStyle ='#bada55';
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.lineWidth = 30;
//參數可調整
ctx.globalCompositeOperation = "overlay";
let isDrawing = false;
let lastX = 0;
let lastY = 0;
let hue = 0;
let direction = true;
function draw(e) {
if(!isDrawing)return // stop
ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`
ctx.beginPath();
//start from
ctx.moveTo(lastX,lastY);
//go to
ctx.lineTo(e.offsetX,e.offsetY);
ctx.stroke();
[lastX,lastY] = [e.offsetX,e.offsetY];
hue++;
if (hue >= 360) {
hue = 0
};
if (ctx.lineWidth >= 100 || ctx.lineWidth <= 1) {
direction = !direction;
}
if (direction) {
ctx.lineWidth++
}else{ ctx.lineWidth-- }
}
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mousedown', (e) => {
isDrawing = true;
[lastX,lastY] = [e.offsetX,e.offsetY];
} );
canvas.addEventListener('mouseup', () => isDrawing = false );
canvas.addEventListener('mouseout', () => isDrawing = false );