Skip to main content

Array

宣告Array和Object

const first = [1,2,3];
const second = [4,5,6];
const third = { name:"James" };
const fourth = { job: "student" };

新增修改Array值

let colors = ['red','green'];
colors[2] = 'blue'; //新增
colors[1] = 'yellow'; //修改

新增修改Object值

let student = {name:'peter', id=12};
student.gender = 'male'; //新增
student.name = 'henry'; //修改

Spread Operator

const combined = first.concat(second); //舊的方式
const combined = [...first, 'a' ,...second, 'b']; //新的方式 中間還可以加上另一個值
const combined2 = {...third, ...fourth, location:"Australia"}; //組合多個object,並可以加上另一個值

Cloning an array

const clone = [...first]; //複製一份array

Cloning an object

const circle = {radius:1, draw(){console.log('draw');}};
const another = object.assign({}, circle); //{}裡面可以有屬性,也可以空白
const another = {...circle}; //最簡便的方法

Loop an array

const colors = ['red','green','blue'];
for(let i=0;i<colors.length;i++){
console.log(colors[i]);
}

for(let i in colors){
console.log(colors[i]);
}

for(let color of colors){
console.log(color);
}

Loop an object

for (let key in objectA){
console.log(objectA[key]);
}

Map 迴圈

myArray.map(item => {
return(
<myComponent key={item.id} item={item} />
);
});

Find 找到其中一個

const [selectedID, setSelectedID] = useState();
const selectedItem = myArray.find(item => item.id === selectedID);

Filter 找到其中多個

const [selectedType, setSelectedType] = useState();
const selectedItems = myArray.filter(item => item.type === selectedType);

Filter 剔除一個

const [recipes, setRecipes] = useState([]);
function handleDelete(id){
setRecipes(recipes.filter(recipe=> recipe.id !== id));
}

增加一個

const [recipes, setRecipes] = useState([]);
function handleAdd(){
const newOne={id:1,name:"pasta"};
setRecipes([...recipes, newOne]);
}

取代一個

const [recipes, setRecipes] = useState([]);
function handleReplace(id, recipe){
const newRecipes = [...recipes];
const index = newRecipes.findIndex((item) => item.id ===id);
newRecipes[index] = recipe;
setRecipes(newRecipes);
}