' P '

whatever I will forget

Certified Javascript Developer Variables, Types, and Collections Section

Variables, Types, and Collections

JSON & JavaScript Object

JSON.stringify()

  • JavaScript Object から JSON Formatに変換.
    • ちなみに、関数がはいっているような場合は、nullになる。
JSON.stringify({ x: [10, undefined, function(){}, Symbol('')] });
// '{"x":[10,null,null,null]}'

JSON.parse()

POST時のフォーマット

  • プロパティと値を ""で囲む.
  • 全体 {}''で囲む
const data = '{ "name": "Jon Smith", "title": "IT Manager", "salary": 100000, "email": "jsmith@cosmicinnovation.com" }';

XMLHttpRequest

  • XMLHttpRequestでWebサーバーから受信したJSONレスポンスには、XMLHttpRequestオブジェクトのプロパティresponseTextを使ってアクセスすることができます.
  • その値をJSONからJavaScriptオブジェクトに変換して、さらに操作する必要があります.
JSON.parse(xhr.responseText);

Functions

prototype

Object.prototype.toString()

Object.prototype.valueOf()

  • valueOfメソッドが存在しない場合は、toStringメソッドが文字列変換に使用されます.
const userObj1 = {
    id: 1,
    name: "Carlos",
    toString: function () {
        return `[User id:${this.id}][User name:${this.name}]`;
    },
};
const userObj2 = {
    id: 2,
    name: "Luis",
    toString: function () {
        return `[User id:${this.id}][User name:${this.name}]`;
    },
    valueOf: function () {
        return this.id;
    }
};

//The developer has initialized an array with the two objects above and iterates the array with a forEach loop as shown below.

let userArray = new Array(userObj1, userObj2);
userArray.forEach((user, index) => {
    console.log("[index=" + index + "]" + user);
    //implementation here
});
  • 出力は下記となります.
[index=0][User id:1][User name:Carlos]
    [index=1]2

splice()

arrayの要素の切り取り、replaceが可能、あるいは要素を追加することも可能な関数

developer.mozilla.org

  • splice(start, deleteCount)の場合
let days = [1, 2, 3, 4, 5, 6, 7];

for (let num of days) {

    if (num == 3) {
        days.splice(1, 2); // [1, 4, 5, 6, 7]
    } else if (num == 6) {
        days.splice(1, 3); // [1, 7]
    }
}

console.log(days);
  • splice(start, deleteCount, item1)の場合
    startのindex位置からdeleteCount分を削除し、その位置にitem1をinsertする
let array = ['one', 1, 'two', 2, 3, 4];

for (let val of array) {
   if (val === 3) {
      array.push('three'); // ["one", 1, "two", 2, 3, 4, "three"]
   }
}

array.splice(1, 1);  // remove 1
console.log(array);  // ["one", "two", 2, 3, 4, "three"]
array.splice(2, 3, 'four'); // remove 2, 3, 4, and insert 'four'
console.log(array); // ["one", "two", "four", "three"]

slice()

  • spliceと同じく切り取りができるのだが、こちらはShallow Copyのため、元の配列は変更されない.

developer.mozilla.org


Array.reduce()

  • 使用すると、配列を 1 つの出力値に縮小・変換することができます.
    • このメソッドは、コールバック関数とオプションのinitialValueをパラメータとして受け取ります.
    • コールバック関数は、元の配列の各要素に対して実行されます.
    • コールバック関数は、accumulator(必須)、currentValue(必須)、index(オプション)、array(オプション)の 4 つの引数を受け取ります.
    • accumulator は、コールバック関数の最後の呼び出しで返された累積値を表します.
      • コールバック変数で返却される値がない場合、undefinedになります.
      • あるいは、array[0]の値.
    • currentValue は、コールバック関数で処理されている現在の要素を表す.
      • あるいは、array[1]の値.
    • initialValue は、accumulatorの初期値を表します.
    • 指定がない場合は、配列の最初の要素が使用されます.
    • ただし、配列の各要素はオブジェクトであるため、initialValue には 0 を指定する必要があります.
    • コールバック関数ではなく reduce() メソッドのパラメータであるため、コールバック関数の後に配置する必要があります。

developer.mozilla.org

www.kwbtblog.com

サンプル1

const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  initialValue
);

console.log(sumWithInitial);
// Expected output: 10

サンプル2

[[0, 1], [2, 3]].reduce(
  (acc, cur) => {
    return acc.concat(cur);
  },
  [1, 2]
);
// [1, 2, 0, 1, 2, 3]
  • 初期値がある場合は、最初にくる.
  • その後はarrayの順序.

サンプル3

[1, 2, 3, 4].reduce((prev, cur) => console.log(prev, cur));

// 1 2
// undefined 3
// undefined 4
  • 最初はarray[0], array[1]の値が表示される.
  • その後、コールバック変数がないため、undefined、現在の値が表示される.

padStart()

  • 文字列の先頭にパディング(指定した文字列か、スペース)を追加できます.
  • param1は、指定文字数(桁)
    • 変更する文字列の桁数が指定されたparam1より多い場合は、何も行われない.
'abc'.padStart(10);         // "       abc"
'abc'.padStart(10, "foo");  // "foofoofabc"
'abc'.padStart(6,"123465"); // "123abc"
'abc'.padStart(8, "0");     // "00000abc"
'abc'.padStart(1);          // "abc"

padEnd()

const str1 = 'Breaded Mushrooms';

console.log(str1.padEnd(25, '.'));
// expected output: "Breaded Mushrooms........"

const str2 = '200';

console.log(str2.padEnd(5));
// expected output: "200  "

flat()

arrayの平坦化を行ってくれる関数
引数を指定しないとデフォルトで1、inifinityを指定すると全ての階層を平坦化する

developer.mozilla.org

const arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]

const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

const arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]

const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Number / Float / String Functions

toFixed()

  • 文字列を返します.
  • 渡された値に基づいて、指定された桁数の文字列をフォーマットします.
  • 数値に小数点以下の数字が含まれていない場合は、ゼロが追加されます.
function financial(x) {
  return Number.parseFloat(x).toFixed(2);
}

console.log(financial(123.456));
// Expected output: "123.46"

console.log(financial(0.004));
// Expected output: "0.00"

console.log(financial('1.23e+5'));
// Expected output: "123000.00"

parseFloat & isInteger

  • isInteger()Number.isInteger()としないと使えない
  • parseFloat()はNumberオブジェクトのメソッドであるがグローバルメソッドのためNumber.の記述は必要ない
console.log(Number.isInteger("1"));
console.log(isInteger("1"));

// ReferenceError: isInteger is not defined

console.log(parseFloat("1"));

Array Fucntions

Array.prototype.forEach()

  • forEach() メソッドを使用して配列を繰り返し処理することができます.
  • このメソッドは、コールバック関数をパラメータとして受け取ります.
  • コールバック関数は、次の順序で 1 つから 3 つの引数を受け取ります:
    • currentValue(必須)、index(オプション)、array(オプション).
array.forEach((item, index) => displayCustomer(index+1, item));

developer.mozilla.org

Array.from()

反復可能オブジェクト、Array風のオブジェクトからArrayインスタンスを生成する

developer.mozilla.org

console.log(Array.from('foo'));
// expected output: Array ["f", "o", "o"]

console.log(Array.from([1, 2, 3], x => x + x));
// expected output: Array [2, 4, 6]

Date Functions

Date.prototype.toUTCString() / Date.prototype.toISOString()

世界協定時間(UTC)のStringに変換する

toString()

ユーザのタイムゾーンを変換、UTCからの差分も表示する

toDateString()

日時に変換。時間は考慮されない

Date.parse()

  • ISO 8601 拡張フォーマットで入力された日付文字列(例:2010-10-10)を受け取り、その日付を 1970 年 1 月 1 日 00:00:00 UTC からのミリ秒数に換算する.

Date.now()

  • 1970年1月1日 00:00:00 UTC からのミリ秒数を返します.

スプレッド構文

配列式や文字列などの反復可能オブジェクトを展開することができる developer.mozilla.org

let numberStore = [0, 1, 2];
let newNumber = 12;
numberStore = [...numberStore, newNumber];

分割代入 (destructuring assignment)

配列やオブジェクトを分割的に代入できる

developer.mozilla.org

  • 配列
    • 再構築する場合は []を使用する
const foo = ['one', 'two', 'three'];

const [red, yellow, green] = foo;
console.log(red); // "one"
console.log(yellow); // "two"
console.log(green); // "three"
  • オブジェクト
    • 再構築す場合は {}を使用する
const user = {
    id: 42,
    isVerified: true
};

const {id, isVerified} = user;

console.log(id); // 42
console.log(isVerified); // true

残余引数

  • 残余引数を用いると、関数に渡された引数の一部を配列として受け取れます.
var f = (a,b, ...val) => {
  return val;
};

console.log(f(1,2,3,4,5)); // 3,4,5

push, pop, shift, unshift関数

  • push: arrayの最後に要素を追加
  • pop: arrayの最後の要素を削除
  • shift: arrayの最初の要素を削除
  • unshift: arrayの最初に要素を追加

filter関数

  • 条件に入れるのは、array内から取得したいもの
  • callback後のarrayにいれたくないものは!など、否定系にすること
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

argumentsオブジェクト

  • 関数に渡された配列風のオブジェクト。
  • 実際に返されるのは object型.
  • 配列ではないので、配列に変換する場合は array.fromを使用する  

developer.mozilla.org

strict mode

  • 有効な場合、変数を使用したり値を代入したりする前に、最初に宣言することが要求されます。
"use strict";
x = 23; // Gives an error since 'x' is not declared
var x; 

var, let, const

varとforループ

  • varはコードブロックのスコープを無視するので、forループ後の iは ループ終了値になっており、そこから関数をcallすると、ループ終了値がprintされる.
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 1);
}
// 3 3 3

note.affi-sapo-sv.com

qiita.com

const

  • オブジェクトや配列の値は、変数自体が定数である場合、つまりconstキーワードを使って宣言されている場合でも、更新が許可されます.
  • letconstで宣言された変数はブロックスコープとなる.
    • 下記コードはreference errorとなる.
function checkAge(age) {
  if (age < 18) {
    const message = "Sorry, you're too young."
  } else {
    const message = "Yay! You're old enough!"
  }

  return message
}

console.log(checkAge(21))

標準オブジェクト

Symbol型

  • プリミティブ型.
  • 見た目は一緒でも必ずユニークになる.
// 2 つのシンボルを同じ説明文で使用
let Sym1 = Symbol("Sym")
let Sym2 = Symbol("Sym")

console.log(Sym1 === Sym2) // "false" を返す
  • 文字列ではないので、明示的に変換が必要.
let Sym = Symbol("Sym")
alert(Sym)  // TypeError: Cannot convert a Symbol value to a string

Number

  • 文字列をセットすると NaNになる.
console.log(Number('true'));