es6 は変数や関数をオブジェクトのプロパティやメソッドとして直接書き込みます。
const name = 'hattie',
age = 18;
const person = {
// name: name,
// age: age,
// sayName: function() {
// console.log(this.name);
// }
//以下はes6での記述方法である。
name,
age,
sayName() {
console.log(this.name);
}
}
person.sayName();
入力されたパラメータをオブジェクトにカプセル化し、そのオブジェクトを返します。
function fn(x, y) {
return {x,y}
}
console.log(fn(1, 2)); //{x: 1, y: 2}
let fn2 = (x, y) => ({x,y});
console.log(fn2(3, 4)); //{x: 3, y: 4}
オブジェクトのes6 set(){}とget(){}は、Javaのsetメソッドとgetメソッドに似ています。
let car = {
wheel: 4,
setWheel(newWheel) {
if (newWheel < this.wheel) {
throw new Error('ライブラリの数を増やす');
}
this.wheel = newWheel;
},
get() {
return this.wheel;
}
}
console.log(car.get());
car.setWheel(5);
console.log(car.get());
オブジェクト変数名の拡張 [].
const name = 'my';
const obj = {
[name + 'name']: 'hattie',
[name + 'fn']() {
console.log(this);
}
}
console.log(obj); //{myname: "hattie", myfn: }
オブジェクトのメソッド
1.is() 比較 ===との違いはNaNのみ
console.log(NaN === NaN); //false
console.log(Object.is(NaN, NaN)); //true
// (method) ObjectConstructor.is(value1: any, value2: any): boolean
//オブジェクトの比較
let a = {1,2};
let b = {1,2};
console.log(a === b); //false
console.log(Object.is(a, b)); //false は比較される参照であり、内容ではない。
//基本的なデータ型の比較
const h = 'we';
const j = 'we';
console.log(h === j); //true
console.log(Object.is(h, j)); //true
2.assign() 後のオブジェクトをターゲット・オブジェクトにマージ Object.assign(target,obj1,boj2...)
let newObj = Object.assign({
a: 1,
add() {
this.a + 2;
}
}, {
b: 2
}, {
a: 3
});
console.log(newObj); //{a: 3, b: 2} 次のオブジェクトがターゲット・オブジェクトと同じ属性名を持つ場合、そのオブジェクトは
配列の拡張
1.から
擬似配列から実配列への変換
//疑似配列を実配列に変換する
let arr = [].slice.call(arguments);
console.log(arr);
let arr2 = Array.from(arguments); //from
console.log(arr2);
let arr3 = [...arguments]; //...
console.log(arr3);
Array.from(array, callback function) コールバック関数は、配列の各要素を処理します。
let lis = document.querySelectorAll('li');
//Array.from(コールバック関数は、配列の各要素を処理する。
let liContents = Array.from(lis, ele => ele.textContent);
console.log(liContents);
2.of() は、任意の型の値の集合を配列に変換します。
console.log(Array.of(1, {a: 1}, [2, 3])); //[1, { }, Array(2)]
3.find() findIndex()
find() 条件にマッチする最初の要素を見つけます findIndex() 条件にマッチする最初の要素のインデックスを見つけます
let num = [1, 2, -10, -].find(n => n < 0);
console.log(num); //-10
let numIndex = [1, 2, -10, -].findIndex(n => n < 0);
console.log(numIndex); //2
4. copywithin() 第 2 パラメータから始まり、第 1 パラメータへのコピーで終わり、同じ番号から上書き。あまり使われません。
console.log([1, 2, 3, 8, 9, 10].copyWithin(0, 2)); //[3, 8, 9, ]
5. entries() keys() values() イテレータ配列イテレータ {} を返します。
... ループ走査の
const arr = ["a", "b", "c"];
for (let index of arr.keys()) {
console.log(index);
}
for (let ele of arr.values()) {
console.log(ele);
}
for (let [index, ele] of arr.entries()) {
console.log(index, ele);
}
6.includes()は、配列が特定の値を含むかどうかをブール値で返します。
[1,2,3].includes(2);
true
[1,2,3].includes('2');
false
[1,2,3].indexOf('2');
-1





