JavaScript実用技術ポイントのまとめ
1162 ワード
1.配列のデバッグ
let a = [null,undefined,1,null,undefined,1,3,3,'1111','444','1111',true,false,false];
let b = [ ...new Set(a) ];
console.log(b); // [null, undefined, 1, 3, "1111", "444", true, false]
2.文字列内の変数のグローバル置換let varItem = [
{
code: 'KHMC',
title: ' '
},
{
code: 'CPMC',
title: ' '
}
];
let msg = ' ${ } ${ } ${ }';
varItem.forEach(i => {
let newReg = eval('\/\\$\\{'+i.title+'\\}\/');
msg = msg.replace(new RegExp(newReg,'g'),'${'+i.code+'}');
});
console.log(msg); // " ${CPMC} ${KHMC} ${CPMC}"
3.配列オブジェクトの属性の並べ替えlet obj = [{age:1},{age:2},{age:10},{age:11},{age:5},{age:99},{age:7}];
function compare(property){
return function(a,b){
let value1 = a[property];
let value2 = b[property];
return value1 - value2;
}
}
let newObj = obj.sort(compare('age'));
console.log(newObj); // [{a:1},{a:2},{a:5},{a:7},{a:10},{a:11},{a:99}];