Javascript Arrayの基本まとめ

Javascript
//アレイの例
const numbers = [43, 22, 42, 56, 12, 3];
const numbers2 = new Array(22, 43, 56, 21, 22);
const fruit = ['Banana', 'Melon', 'Pear', 'Apple'];
const mixed = [22, 'Good', true, undefined, null, { a: 1, b: 2 }, new Date()];

let val;

console.log(numbers); //[43, 22, 42, 56, 12, 3]
console.log(val); //undefined

val = numbers.length;
console.log(val); //6

val = Array.isArray(numbers);
console.log(val); //true

val = numbers[3];
console.log(val); //56

val = numbers[0];
console.log(val); //43

numbers[2] = 100;
console.log(numbers); //[43, 22, 100, 56, 12, 3]

val = numbers.indexOf(12);
console.log(val); //4

numbers.push(250);
console.log(numbers); //[43, 22, 100, 56, 12, 3, 250]

numbers.unshift(120);
console.log(numbers); //[120, 43, 22, 100, 56, 12, 3, 250]

numbers.pop();
console.log(numbers); //[120, 43, 22, 100, 56, 12, 3]

numbers.shift();
console.log(numbers); //[43, 22, 100, 56, 12, 3]

numbers.splice(1, 3);
console.log(numbers); //[43, 12, 3]

numbers.reverse();
console.log(numbers); //[3, 12, 43]

val = numbers.concat(numbers2);
console.log(val); //[3, 12, 43, 22, 43, 56, 21, 22]

val = fruit.sort();
console.log(val); //['Banana', 'Melon', 'Pear', 'Apple'] => ["Apple", "Banana", "Melon", "Pear"]

val = numbers.sort();
console.log(val); //[12, 3, 43] 最初の数字でソートされている

val = numbers.sort(function(x, y) {
  return x - y;
});
console.log(val); //[3, 12, 43]

val = numbers.sort(function(x, y) {
  return y - x;
});
console.log(val); //[43, 12, 3]

console.log(numbers); //[43, 12, 3]
const numbers3 = [43, 22, 42, 56, 12, 3];
console.log(numbers3); // [43, 22, 42, 56, 12, 3]
function under50(num) {
  return num < 50;
}
val = numbers3.find(under50);
console.log(val); //43

コメント