members=[
'kim',
'choi',
'park'
];
members.splice(1,2);
We delete elements of array using splice method. We first put the starting index as a first parameter, and the number of element that we want to delete as a second parameter. Meanwhile, the meaning of splice(1,2) is delete 2 elements from starting index 1. Therefore, only 'kim' will remain after the splice method is executed.
members.splice(1,2,'Lee');
If there is a third parameter, we insert a value to where we delete elements. Therefore, 'kim', 'lee' will remain after the splice method is ececuted.
members.splice(1,1,'Lee');
change 1st index value to 'Lee'.
members.splice(1,2,'Lee','Han');
change multiple values at once.
//members.splice(-1,1);
members.splice(members.length - 1,1);
use a second sentence not a first sentence to delete a last element in array.
numbers.splice(0, 0, 1, 2, 3, 5, 8, 9);
We can add multiple elements like this. It means delete 0 element from starting index 0. Therefore, delete no elements and add 6 elements(1, 2, 3, 5, 8, 9).
let j=0;
let len=numbers.length;
for(let i=0;i<len;i++){
if(numbers[j]%2===1){
numbers.splice(j,1);
}else{
j=j+1;
}
}
instead of this code,
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 !== 0) {
numbers.splice(i, 1);
i--;
}
}
use this code. Keep in mind that we can do - i as well.
'프로그래밍' 카테고리의 다른 글
2023-05-16 javascript_array (0) | 2023.05.16 |
---|---|
2023-05-13 javascript (0) | 2023.05.13 |
2023-05-08 javascript (0) | 2023.05.08 |
2023-05-07 javascript (0) | 2023.05.07 |
2021/12/16 C언어 메모(백준) (0) | 2021.12.16 |