Tip JavaScript Hữu Ích

Post Reply
haihoang
Posts: 7
Joined: Fri Apr 19, 2019 10:49 am

Tip JavaScript Hữu Ích

Post by haihoang »

  • 1. Giải quyết phần tử lặp trong mảng bằng cách sử dụng Set.

Code: Select all

var j = [...new Set([1, 2, 3, 3])]
>> [1, 2, 3]
  • 2. Lọc các falsy values (0, undefined, null, false, vv.) ra khỏi một array

Code: Select all

myArray
    .map(item => {
        // ...
    })
    // Get rid of bad values
    .filter(Boolean);
  • 3. Tạo empty object JS

Code: Select all

let dict = Object.create(null);
  • 4. Merge Objects JS

Code: Select all

const person = { name: 'David Walsh', gender: 'Male' };
const tools = { computer: 'Mac', editor: 'Atom' };
const attributes = { handsomeness: 'Extreme', hair: 'Brown', eyes: 'Blue' };

const summary = {...person, ...tools, ...attributes};
/*
Object {
  "computer": "Mac",
  "editor": "Atom",
  "eyes": "Blue",
  "gender": "Male",
  "hair": "Brown",
  "handsomeness": "Extreme",
  "name": "David Walsh",
}
*/
  • 5. Require Function Parameters JS

Code: Select all

const isRequired = () => { throw new Error('param is required'); };

const hello = (name = isRequired()) => { console.log(`hello ${name}`) };

hello(null);
hello('David');
  • 6. Get Query String Parameters JS

Code: Select all

// Assuming "?post=1234&action=edit"

var urlParams = new URLSearchParams(window.location.search);

console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1"
  • 7. Default Parameters JS

Code: Select all

let a = null
let dict = a || 1 
console.log(a) // 1
Hai Hoang

Post Reply