242. Valid Anagram

242. Valid Anagram

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
var isAnagram = function (s, t) {
    const a = s.split('').sort().join('');
    const b = t.split('').sort().join('');
    if (a === b) {
        return true;
    } else {
        return false;
    }
};

Array.prototype.splice()

splice 可以將原本的陣列進行新增或刪除元素。

基本語法

splice(start, deleteCount, item1, item2, /* …, */ itemN)

// start 起始位置
// deleteCount 要刪除的個數
// item1, item2, ... 欲新增的元素

Array.prototype.slice()

slice 可以截取部分陣列裡面的元素成另一個新的陣列。

基本語法

slice(start, end)
// start 起始位置
// end 結束位置(但不包含)

Array.prototype.join()

join 可以將陣列裡面的元素以字串的形式連接起來。

基本語法

join() // 預設是用 comma (,) 連接
join(separator) // separator 代表元素之間連接的字串

const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// Expected output: "Fire,Air,Water"

console.log(elements.join(''));
// Expected output: "FireAirWater"

console.log(elements.join('-'));
// Expected output: "Fire-Air-Water"

String.prototype.split()

split 將原本字串切割成一個含有子字串的陣列。

基本語法

split() // 回傳一個含有原本字串的陣列

split(separator) // separator 被拿來當作切割的字串

split('') // 切割每一個字串

const sentence = 'Hello, how are you?';

const words1 = sentence.split(' '); //  ["Hello,", "how", "are", "you?"]

const words2 = sentence.split(''); //  ['H', 'e', 'l', 'l', 'o', ',', ' ', 'h', 'o', 'w', ' ', 'a', 'r', 'e', ' ', 'y', 'o', 'u', '?']

const words3 = sentence.split(); //  ['Hello, how are you?']