(10)內(nèi)置對象-1

內(nèi)置對象

我們平時忙于開發(fā),很少有時間能夠?qū)⑽臋n看一遍。這樣在很多時候,我們本可以一個原生方法能夠?qū)崿F(xiàn)的程序,卻累的跟狗一樣,寫出來的程序還不定好使。為了減少重復(fù)造輪子的時間,將MDN的API結(jié)合自己的理解,歸納整理了下面的文檔。MDN文檔-JavaScript內(nèi)置對象

1 Array對象

  • arr.length:獲取數(shù)組元素的長度
var arr = ['Tom','John','Amy'];
arr.length    // 3
  • arr.concat():合并兩個或多個數(shù)組
var arr1 = ['a', 'b', 'c'];
var arr2 = ['d', 'e', 'f'];
var arr3 = arr1.concat(arr2);    // [ "a", "b", "c", "d", "e", "f" ]
  • arr.join(str):將arr以指定字符連接成字符串
var arr = ['Tom','John','Amy'];
arr.join('#');    // Tom#John#Amy
  • arr.push():在數(shù)組末尾推入指定元素
var arr = ['Tom','John','Amy'];
arr.push('Jack');    // 4
arr        // ['Tom','John','Amy','Jack']
  • arr.pop():彈出并返回數(shù)組末尾元素
var arr = ['Tom','John','Amy'];
arr.pop();    // Amy
arr        // ['Tom','John']
  • arr.shift():彈出并返回數(shù)組第一個元素
var arr = ['Tom','John','Amy'];
arr.shift();    // Tom
arr        // ['John','Amy']
  • arr.unshift():在數(shù)組開頭處添加指定元素
var arr = ['Tom','John','Amy'];
arr.unshift('Jack');    // 4
arr        // ['Jack',Tom','John','Amy']
  • arr.sort([函數(shù):排序規(guī)則]):排序(默認采用字符串順序排序,數(shù)字排序則需要通過自定義函數(shù)實現(xiàn))
var arr = ['Tom','John','Amy'];
arr.sort();    // ["Amy", "John", "Tom"]
arr        // 改變原數(shù)組:["Amy", "John", "Tom"]
  • arr.reverse():數(shù)組元素順序反轉(zhuǎn)
var arr = ["Amy", "John", "Tom"];
arr.reverse()    // ['Tom', 'John', 'Amy']
  • arr.indexOf():獲取指定元素在數(shù)組中的位置,不存在返回-1
var arr = ["Amy", "John", "Tom"];
arr.indexOf('John');    // 1
arr.indexOf('David');    // -1
  • arr.lastIndexOf():獲取指定元素最后一次出現(xiàn)的位置,不存在返回-1
var arr = ["Amy", "John", "Tom", "David", "Tom", "Jeff"];
arr.lastIndexOf('Tom');    // 4
arr.lastIndexOf('James');    // -1
  • arr.slice(起始位置,結(jié)束位置):獲取數(shù)組中指定的片段(不包含結(jié)束位置) - 復(fù)制數(shù)組
var arr = ["Amy", "John", "Tom", "David", "Jeff"];
arr.slice(2)    // ["Tom", "David", "Jeff"]
arr            // 原數(shù)組不發(fā)生變化,["Amy", "John", "Tom", "David", "Jeff"]

var arr = ["Amy", "John", "Tom", "David", "Jeff"];
arr.slice(2,4)    // 不包含結(jié)束位置 ["Tom", "David"]    
  • arr.splice(起始位置,長度):從數(shù)組中添加或刪除元素。
var arr = ["Amy", "John", "Tom", "David", "Jeff"];
arr.splice(2)    // ["Tom", "David", "Jeff"]
arr            // 原數(shù)組發(fā)生變化,["Amy", "John"]

var arr = ["Amy", "John", "Tom", "David", "Jeff"];
arr.splice(2,2)    // ["Tom", "David"]
arr            // 原數(shù)組發(fā)生變化,["Amy", "John", "Jeff"]
  • arr.forEach(callback[, thisArg]): 對數(shù)組的每個元素執(zhí)行一次提供的函數(shù)
var arr = ["Amy", "John", "Tom"];

arr.forEach(function(element) {
  console.log(element);
});

// expected output: "Amy"
// expected output: "John"
// expected output: "Tom"

注意:
1. forEach 遍歷的范圍在第一次調(diào)用 callback 前就會確定
2. 調(diào)用 forEach 后添加到數(shù)組中的項不會被 callback 訪問到
3. 如果已經(jīng)存在的值被改變,則傳遞給 callback 的值是 forEach 遍歷到他們那一刻的值。
4. 已刪除的項不會被遍歷到
5. 如果已訪問的元素在迭代時被刪除了(例如使用 shift()),之后的元素將被跳過
6. forEach() 為每個數(shù)組元素執(zhí)行callback函數(shù);不像 map() 或者 reduce(),它總是返回 undefined 值,并且不可鏈式調(diào)用
7. forEach() 被調(diào)用時,不會改變原數(shù)組(即調(diào)用它的數(shù)組),即使傳遞的參數(shù)里的 callback被調(diào)用時可能會改變原數(shù)組
8. 沒有辦法中止或者跳出 forEach() 循環(huán),除了拋出一個異常
    需要終止:
    1. 簡單for循環(huán)
    2. for...of循環(huán)
    3. arr.every()
    4. arr.some()
    5. arr.find()
    6. arr.findIndex()
    7. 先使用filter再forEach也可以
9. 如果使用箭頭函數(shù),第二個thisArg參數(shù)忽略  
  • arr.every():檢測數(shù)值元素的每個元素是否都符合條件。
var arr = [16,22,15,33,38,28];

// 要求:數(shù)組中的每個元素的值都必須大于18為true,其余都為假
arr.every(function(value){
    return value > 18;
})    // false
  • arr.some():檢測數(shù)組元素中是否有元素符合指定條件。
var arr = [16,22,15,33,38,28];

// 要求:數(shù)組中的每個元素都小于18為true,其余都為真
arr.some(function(value){
    return value > 18;
})        // true

  • arr.map():通過指定函數(shù)處理數(shù)組的每個元素,并返回處理后的數(shù)組
var arr = [16,22,15,33,38,28];

// 要求:數(shù)組中的每個元素的值都必須大于18為true,其余都為假
arr.map(function(value){
    return value + 10;
})    // [26,32,25,43,48,38]
  • arr.filter():檢測數(shù)值元素,并返回符合條件所有元素的數(shù)組。
var arr = [16,22,15,33,38,28];

// 要求:數(shù)組中超過18的元素都被篩選出來
arr.filter(function(value){
    return value > 18;
})    // [22,33,38,28]
  • Array.isArray():判斷是否是一個數(shù)組
Array.isArray([1, 2, 3]);      // true
Array.isArray({foo: 123});    // false
Array.isArray("foobar");  // false
Array.isArray(undefined);  // false

與instanceof區(qū)別:
Array.isArray()能檢測iframes,instanceof不能檢測

// 案例
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
xArray = window.frames[window.frames.length-1].Array;
var arr = new xArray(1,2,3); // [1,2,3]

// Correctly checking for Array
Array.isArray(arr);  // true
// Considered harmful, because doesn't work though iframes
arr instanceof Array; // false
  • array.reduce(callback,initnum):累加器和數(shù)組中的每個元素(從左到右)應(yīng)用一個函數(shù),將其減少為單個值
  • 對數(shù)組中的每個元素執(zhí)行一個由您提供的reducer函數(shù)(升序執(zhí)行),將其結(jié)果匯總為單個返回值
  • array.reduceRight(callback,initnum):接受一個函數(shù)作為累加器(accumulator)和數(shù)組的每個值(從右到左)將其減少為單個值。
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array){
    return accumulator + currentValue;
});    // 最終結(jié)果:10

accumulator:計算值
currentValue: 當前值
currentIndex: 當前索引值
array: 處理的數(shù)組
callback 計算值 當前值 當前索引 處理的數(shù)組 返回值
第一次調(diào)用 0 1 1 [0, 1, 2, 3, 4] 1
第二次調(diào)用 1 2 2 [0, 1, 2, 3, 4] 3
第三次調(diào)用 3 3 3 [0, 1, 2, 3, 4] 6
第四次調(diào)用 6 4 4 [0, 1, 2, 3, 4] 10

可以完成的事情:

  1. 數(shù)組所有值求和(案例同上)

  2. 累加對象數(shù)組的值

    var initialValue = 0;
    var sum = [{x: 1}, {x:2}, {x:3}].reduce(
        (accumulator, currentValue) => accumulator + currentValue.x
        ,initialValue
    );
    
    console.log(sum) // logs 6
    
  1. 將二維數(shù)組轉(zhuǎn)為一維數(shù)組

    var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
      function(a, b) {
        return a.concat(b);
      },
      []
    );
    // flattened is [0, 1, 2, 3, 4, 5]
    
  2. 計算數(shù)組中每個元素出現(xiàn)的次數(shù)

    var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
    
    var countedNames = names.reduce(function (allNames, name) { 
      if (name in allNames) {
        allNames[name]++;
      }
      else {
        allNames[name] = 1;
      }
      return allNames;
    }, {});
    // countedNames is:
    // { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
    
  3. 按屬性對object分類

    var people = [
      { name: 'Alice', age: 21 },
      { name: 'Max', age: 20 },
      { name: 'Jane', age: 20 }
    ];
    
    function groupBy(objectArray, property) {
      return objectArray.reduce(function (acc, obj) {
        var key = obj[property];
        if (!acc[key]) {
          acc[key] = [];
        }
        acc[key].push(obj);
        return acc;
      }, {});
    }
    
    var groupedPeople = groupBy(people, 'age');
    // groupedPeople is:
    // { 
    //   20: [
    //     { name: 'Max', age: 20 }, 
    //     { name: 'Jane', age: 20 }
    //   ], 
    //   21: [{ name: 'Alice', age: 21 }] 
    // }
    
  4. 使用擴展運算符和initialValue綁定包含在對象數(shù)組中的數(shù)組

  5. // friends - 對象數(shù)組
    // where object field "books" - list of favorite books 
    var friends = [{
      name: 'Anna',
      books: ['Bible', 'Harry Potter'],
      age: 21
    }, {
      name: 'Bob',
      books: ['War and peace', 'Romeo and Juliet'],
      age: 26
    }, {
      name: 'Alice',
      books: ['The Lord of the Rings', 'The Shining'],
      age: 18
    }];
    
    // allbooks - list which will contain all friends' books +  
    // additional list contained in initialValue
    var allbooks = friends.reduce(function(prev, curr) {
      return [...prev, ...curr.books];
    }, ['Alphabet']);
    
    // allbooks = [
    //   'Alphabet', 'Bible', 'Harry Potter', 'War and peace', 
    //   'Romeo and Juliet', 'The Lord of the Rings',
    //   'The Shining'
    // ]
    
  6. 數(shù)組去重

    let arr = [1,2,1,2,3,5,4,5,3,4,4,4,4];
    let result = arr.sort().reduce((init, current) => {
        if(init.length === 0 || init[init.length-1] !== current) {
            init.push(current);
        }
        return init;
    }, []);
    console.log(result); //[1,2,3,4,5]
    
  7. 按順序運行promise

    /**
     * Runs promises from array of functions that can return promises
     * in chained manner
     *
     * @param {array} arr - promise arr
     * @return {Object} promise object
     */
    function runPromiseInSequence(arr, input) {
      return arr.reduce(
        (promiseChain, currentFunction) => promiseChain.then(currentFunction),
        Promise.resolve(input)
      );
    }
    
    // promise function 1
    function p1(a) {
      return new Promise((resolve, reject) => {
        resolve(a * 5);
      });
    }
    
    // promise function 2
    function p2(a) {
      return new Promise((resolve, reject) => {
        resolve(a * 2);
      });
    }
    
    // function 3  - will be wrapped in a resolved promise by .then()
    function f3(a) {
     return a * 3;
    }
    
    // promise function 4
    function p4(a) {
      return new Promise((resolve, reject) => {
        resolve(a * 4);
      });
    }
    
    const promiseArr = [p1, p2, f3, p4];
    runPromiseInSequence(promiseArr, 10)
      .then(console.log);   // 1200
    
  8. 功能型函數(shù)管道

    // Building-blocks to use for composition
    const double = x => x + x;
    const triple = x => 3 * x;
    const quadruple = x => 4 * x;
    
    // Function composition enabling pipe functionality
    const pipe = (...functions) => input => functions.reduce(
        (acc, fn) => fn(acc),
        input
    );
    
    // Composed functions for multiplication of specific values
    const multiply6 = pipe(double, triple);
    const multiply9 = pipe(triple, triple);
    const multiply16 = pipe(quadruple, quadruple);
    const multiply24 = pipe(double, triple, quadruple);
    
    // Usage
    multiply6(6); // 36
    multiply9(9); // 81
    multiply16(16); // 256
    multiply24(10); // 240
    
  • ES6數(shù)組方法

  • arr.includes(查找元素, 起始位置):判斷一個數(shù)組是否包含一個指定的值,如果是,酌情返回 true或 false

[1, 2, 3].includes(2);    // true
[1, 2, 3].includes(4);    // false
[1, 2, 3].includes(3, 3);  // false
[1, 2, 3].includes(3, -1); // true
[1, 2, NaN].includes(NaN); // true
  • arr.from(arrayLike[, mapFn[, thisArg]]): 從一個類似數(shù)組或可迭代對象中創(chuàng)建一個新的數(shù)組實例。
arrayLike: 想要轉(zhuǎn)換成數(shù)組的偽數(shù)組對象或可迭代對象
mapFn: 如果指定了該參數(shù),新數(shù)組中的每個元素會執(zhí)行該回調(diào)函數(shù)
thisArg: 可選參數(shù),執(zhí)行回調(diào)函數(shù) mapFn 時 this 對象

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

console.log(Array.from([1, 2, 3], x => x + x));
// Array [2, 4, 6]
  • Array.of(): 創(chuàng)建一個具有可變數(shù)量參數(shù)的新數(shù)組實例,而不考慮參數(shù)的數(shù)量或類型
Array.of(7);       // [7] 
Array.of(1, 2, 3); // [1, 2, 3]

Array(7);          // [ , , , , , , ]
    注意:這是指一個有7個空位(empty)的數(shù)組,而不是由7個undefined組成的數(shù)組
Array(1, 2, 3);    // [1, 2, 3]
  • arr.copyWithin(target[, start[, end]]): 淺復(fù)制數(shù)組的一部分到同一數(shù)組中的另一個位置,并返回它,不會改變原數(shù)組的長度
var array1 = ['a', 'b', 'c', 'd', 'e'];

// copy to index 0 the element at index 3
console.log(array1.copyWithin(0, 3, 4));
// expected output: Array ["d", "b", "c", "d", "e"]

// copy to index 1 all elements from index 3 to the end
console.log(array1.copyWithin(1, 3));
// expected output: Array ["d", "d", "e", "d", "e"]
  • Array.prototype.entries():返回一個新的Array Iterator對象,該對象包含數(shù)組中每個索引的鍵/值對。
var array1 = ['a', 'b', 'c'];

var iterator1 = array1.entries();

console.log(iterator1.next().value);
// expected output: Array [0, "a"]

console.log(iterator1.next().value);
// expected output: Array [1, "b"]
  • arr.fill(value[, start[, end]]):用一個固定值填充一個數(shù)組中從起始索引到終止索引內(nèi)的全部元素。不包括終止索引。
var array1 = [1, 2, 3, 4];

// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]

// fill with 5 from position 1
console.log(array1.fill(5, 1));
// expected output: [1, 5, 5, 5]

console.log(array1.fill(6));
// expected output: [6, 6, 6, 6]
  • arr.find(callback[, thisArg]):返回數(shù)組中滿足提供的測試函數(shù)的第一個元素的值。否則返回 undefined。
// 簡單案例
var array1 = [5, 12, 8, 130, 44];

var found = array1.find(function(element) {
  return element > 10;
});

console.log(found);
// expected output: 12

// 更多場景
var array2 = [{ id: 1, name: 'John' }, { id: 2, name: 'Tom' }, { id: 3, name: 'Amy' }];

var found = array2.find(function(element) {
  return element.id === 2;
});

console.log(found);
// expected output: { id: 2, name: 'Tom' }
  • arr.findIndex(callback[, thisArg]):返回數(shù)組中滿足提供的測試函數(shù)的第一個元素的索引。否則返回 undefined。
// 簡單使用
var array1 = [5, 12, 8, 130, 44];

var found = array1.findIndex(function(element) {
  return element > 10;
});

console.log(found);
// expected output: 1

// 更多場景
var array2 = [{ id: 1, name: 'John' }, { id: 2, name: 'Tom' }, { id: 3, name: 'Amy' }];

var found = array2.findIndex(function(element) {
  return element.id === 2;
});

console.log(found);
// expected output: 1
  • arr.flat(depth):按照一個可指定的深度遞歸遍歷數(shù)組,并將所有元素與遍歷到的子數(shù)組中的元素合并為一個新數(shù)組返回。(兼容性問題大)
// 扁平化嵌套數(shù)組
var arr1 = [1, 2, [3, 4]];
arr1.flat(); 
// [1, 2, 3, 4]

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

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

//使用 Infinity 作為深度,展開任意深度的嵌套數(shù)組
arr3.flat(Infinity); 
// [1, 2, 3, 4, 5, 6]

// 扁平化與移除數(shù)組空項
var arr4 = [1, 2, , 4, 5];
arr4.flat();
// [1, 2, 4, 5]

替代方案1: 一層嵌套

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

// 反嵌套一層數(shù)組
arr1.reduce((acc, val) => acc.concat(val), []);// [1, 2, 3, 4]

// 或使用 ...
const flatSingle = arr => [].concat(...arr);

替代方案2: 無限層嵌套

// 使用 reduce、concat 和遞歸無限反嵌套多層嵌套的數(shù)組
var arr1 = [1,2,3,[1,2,3,4, [2,3,4]]];

function flattenDeep(arr1) {
   return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
}
flattenDeep(arr1);
// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]

替代方案3: 使用stack嵌套

// 不使用遞歸,使用 stack 無限反嵌套多層嵌套數(shù)組
var arr1 = [1,2,3,[1,2,3,4, [2,3,4]]];
function flatten(input) {
  const stack = [...input];
  const res = [];
  while (stack.length) {
    // 使用 pop 從 stack 中取出并移除值
    const next = stack.pop();
    if (Array.isArray(next)) {
      // 使用 push 送回內(nèi)層數(shù)組中的元素,不會改動原始輸入 original input
      stack.push(...next);
    } else {
      res.push(next);
    }
  }
  // 使用 reverse 恢復(fù)原數(shù)組的順序
  return res.reverse();
}
flatten(arr1);// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
  • arr.keys():返回一個包含數(shù)組中每個索引鍵的Array Iterator對象
var array1 = ['a', 'b', 'c'];
var iterator = array1.keys();

for (let key of iterator) {
  console.log(key); // expected output: 0 1 2
}
  • arr.values(): 返回一個新的 Array Iterator 對象,該對象包含數(shù)組每個索引的值
const array1 = ['a', 'b', 'c'];
const iterator = array1.values();

for (const value of iterator) {
  console.log(value); // expected output: "a" "b" "c"
}
  • arr.flatMap(): 首先使用映射函數(shù)映射每個元素,然后將結(jié)果壓縮成一個新數(shù)組。它與 map 和 深度值1的 flat 幾乎相同,但 flatMap 通常在合并成一種方法的效率稍微高一些
var new_array = arr.flatMap(function callback(currentValue[, index[, array]]) {
    // 返回新數(shù)組的元素
}[, thisArg])
var arr1 = [1, 2, 3, 4];

arr1.map(x => [x * 2]); 
// [[2], [4], [6], [8]]

arr1.flatMap(x => [x * 2]);
// [2, 4, 6, 8]

// 只會將 flatMap 中的函數(shù)返回的數(shù)組 “壓平” 一層
arr1.flatMap(x => [[x * 2]]);
// [[2], [4], [6], [8]]

flatMap和flat區(qū)別:

let arr = ["今天天氣不錯", "", "早上好"]

arr.map(s => s.split(""))
// [["今", "天", "天", "氣", "不", "錯"],[""],["早", "上", "好"]]

arr.flatMap(s => s.split(''));
// ["今", "天", "天", "氣", "不", "錯", "", "早", "上", "好"]

等價于:歸納(reduce)與合并(concat)

var arr1 = [1, 2, 3, 4];

arr1.flatMap(x => [x * 2]);
// 等價于
arr1.reduce((acc, x) => acc.concat([x * 2]), []);
// [2, 4, 6, 8]

2 Boolean對象

new Boolean([value]): 布爾值的對象包裝器
Boolean(): 其他類型轉(zhuǎn)換為布爾值

注意:上面兩種方式不能搞混
if (new Boolean(0)) {
    // 代碼執(zhí)行,對象為真
}

if (Boolean(0)) {
    // 代碼不執(zhí)行
}

自身屬性:

Boolean.length:1
Boolean.prototype: Boolean構(gòu)造函數(shù)的原型對象

繼承的屬性和方法

Boolean.prototype.toString(): 返回字符串"true"或者"false"
Boolean.prototype.valueOf(): 返回Boolean對象的原始值

3 Date對象

new Date()
new Date(Unix 時間戳)
new Date(dateString):注意這種格式的兼容性
new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds)

注意:
1. 將Date作為構(gòu)造函數(shù)使用,得到Date對象
2. 將Date作為常規(guī)函數(shù)調(diào)用,返回字符串,非Date對象
3. month從0-11,代表1-12月
4. 如果傳入的值超過合理范圍,相鄰的數(shù)值會自動調(diào)整
    13月=>下一年的1月
    70分鐘=>下一個小時的10分鐘
5. 上面第四種方式,前兩個參數(shù)必須傳遞,后面如果沒有值,默認為1(天)或者0(時分秒毫秒)
6. UTC:格林威治時間,Locale:本地時間

屬性:

  1. Date.prototype: 允許為Date對象添加屬性
  2. Date.length: 7

方法:

  1. Date.now(): 返回自 1970-1-1 00:00:00 UTC(世界標準時間)至今所經(jīng)過的毫秒數(shù)。
  2. Date.parse(): 解析一個表示日期的字符串,并返回從 1970-1-1 00:00:00 所經(jīng)過的毫秒數(shù)。
  3. Date.UTC(): 接受和構(gòu)造函數(shù)最長形式的參數(shù)相同的參數(shù)(從2到7),并返回從 1970-01-01 00:00:00 UTC 開始所經(jīng)過的毫秒數(shù)。

所有Date實例繼承Date.prototype

Date.prototype方法

  1. d.getDate()/d.getUTCDate(): 獲取第幾天(1-31)

  2. d.getDay()/d.getUTCDay(): 獲取星期的第幾天(0-6)

  3. d.getFullYear()/d.getUTCFullYear(): 獲取指定日期對象的年份

  4. d.getHours()/d.getUTCHours(): 獲取小時數(shù)

  5. d.getMilliseconds()/d.getUTCMilliseconds(): 獲取毫秒數(shù)

  6. d.getMinutes()/d.getUTCMinutes(): 獲取分鐘數(shù)

  7. d.getMonth()/d.getUTCMonth(): 獲取月份(0-11)

  8. d.getSeconds()/d.getUTCSeconds: 獲取毫秒數(shù)(0-59)

  9. d.getTime(): 返回從1970-1-1 00:00:00 UTC(協(xié)調(diào)世界時)到該日期經(jīng)過的毫秒數(shù),對于1970-1-1 00:00:00 UTC之前的時間返回負值。

上述所有的get方法都對應(yīng)他們的set方法

  1. d.setDate(): 設(shè)置每月的第幾天(1-31)
  2. d.setFullYear(): 設(shè)置指定年份
  3. d.setHours(): 設(shè)置小時數(shù)
  4. d.setMilliseconds(): 設(shè)置毫秒數(shù)
  5. d.setMinutes(): 設(shè)置分鐘數(shù)
  6. d.setMonth(): 設(shè)置月份(0-11)
  7. d.setSeconds(): 設(shè)置毫秒數(shù)(0-59)
  8. d.setTime(): 通過指定從 1970-1-1 00:00:00 UTC 開始經(jīng)過的毫秒數(shù)來設(shè)置日期對象的時間,對于早于 1970-1-1 00:00:00 UTC的時間可使用負值。

其他方法:

  1. d.toDateString():返回日期部分字符串
  2. d.toLocaleDateString():返回一個表示該日期對象日期部分的字符串,該字符串格式與系統(tǒng)設(shè)置的地區(qū)關(guān)聯(lián)。
  3. d.toLocaleTimeString():返回一個表示該日期對象時間部分的字符串,該字符串格式與系統(tǒng)設(shè)置的地區(qū)關(guān)聯(lián)。
  4. d.toLocaleString():返回一個表示該日期對象的字符串,該字符串格式與系統(tǒng)設(shè)置的地區(qū)關(guān)聯(lián)。
  5. d.toString():返回一個表示該日期對象的字符串。
  6. d.valueOf():返回一個日期對象的原始值(時間戳)

4 Math對象

Math不是構(gòu)造器,所有的屬性和額方法都是靜態(tài)的。

屬性

  • Math.PI:圓周率(3.15159)
  • Math.E:歐拉常數(shù)
  • Math.LN2:2的自然對數(shù)
  • Math.LN10:10的自然對數(shù)
  • Math.LOG2E:以2為底E的對數(shù)
  • Math.LOG10E:以10為底E的對數(shù)
  • Math.SQRT1_2:1/2的平方根,約等于0.707
  • Math.SQRT2:2的平方根,約等于1.414

方法

  • Math.abs():絕對值

  • Math.ceil():進一取整

  • Math.floor():舍去取整

  • Math.round():四舍五入

  • Math.max():獲取最大值

  • Math.min():獲取最小值

  • Math.random():獲取隨機數(shù)

function rand(m,n){
    return Math.floor(Math.random()*(n-m+1)+m);
}
  • Math.sin()/Math.sinh()/Math.asinh(): 正弦值/雙曲正弦值/反雙曲正弦值
  • Math.cos()/Math.acos()/Math.acosh(): 余弦值/反余弦值/反雙曲余弦值
  • Math.tan()/Math.atan()/Math.atanh()/Math.atan2(): 正切值/以介于 -PI/2 與 PI/2 弧度之間的數(shù)值來返回 x 的反正切值/反雙曲正切值/返回 y/x 的反正切值.
  • Math.asin()
  • Math.acos()
  • Math.atan()
  • Math.tan2()
三角函數(shù)是以弧度返回值的,通過除法Math.PI/180把弧度轉(zhuǎn)換為角度,也可以通過其他方法轉(zhuǎn)換。
  • Math.cbrt(): 返回x的立方根
  • Math.log(): 返回一個數(shù)的自然對數(shù)
  • Math.log1p(): 返回 1 加上一個數(shù)字的的自然對數(shù)
  • Math.log10(): 返回以10為底數(shù)的x的對數(shù)。
  • Math.log2(): 返回以2為底數(shù)的x的對數(shù)。
  • Math.pow(): 返回x的y次冪.
  • Math.round(): 四舍五入的整數(shù)
  • Math.sign(): 返回x的符號函數(shù), 判定x是正數(shù),負數(shù)還是0.
  • Math.sqrt(): 平方根

5 Number對象

主要功能:用來執(zhí)行類型轉(zhuǎn)換。

屬性:

  • Number.EPSILON:屬性的值接近于 2.2204460492503130808472633361816E-16,或者2-52。

    測試是否相等:
    console.log(0.3 - 0.2 === 0.1);   // false
    console.log(Math.abs(0.3 - 0.2 - 0.1) < Number.EPSILON);  // true
    
  • Number.MAX_SAFE_INTEGER:最大的安全整數(shù)(2的53次方-1)

  • Number.MIN_SAFE_INTEGER:最小的安全整數(shù)(-2的53次方-1)

  • Number.MAX_VALUE:能表示的最大正數(shù)

  • Number.MIN_VALUE:能表示的最小正數(shù)即最接近 0 的正數(shù) (實際上不會變成 0)

  • Number.NaN:特殊的“非數(shù)字”值

  • Number.NEGATIVE_INFINITY:屬性表示負無窮大

  • Number.POSITIVE_INFINITY 屬性表示正無窮大

方法:

  • Number.isFinite() 方法用來檢測傳入的參數(shù)是否是一個有窮數(shù)(finite number)。

  • Number.isInteger() 方法用來判斷給定的參數(shù)是否為整數(shù)。

  • Number.isNaN() 方法確定傳遞的值是否為 NaN和其類型是 Number。它是原始的全局isNaN()的更強大的版本。

  • Number.isSafeInteger() 方法用來判斷傳入的參數(shù)值是否是一個“安全整數(shù)”(safe integer)。一個安全整數(shù)是一個符合下面條件的整數(shù):

  • Number.parseFloat() 方法可以把一個字符串解析成浮點數(shù)。

  • Number.parseInt() 方法依據(jù)指定基數(shù) [ 參數(shù) radix 的值],把字符串 [ 參數(shù) string 的值] 解析成整數(shù)。

  • num.toExponential() 方法以指數(shù)表示法返回該數(shù)值字符串表示形式。

  • num.toFixed()方法使用定點表示法來格式化一個數(shù)。

  • num.toPrecision()方法以指定的精度返回該數(shù)值對象的字符串表示。

  • num.toString() 方法返回指定 Number 對象的字符串表示形式。

  • num.valueOf() 方法返回一個被 Number 對象包裝的原始值。

    注意:
    1. 安全整數(shù):IEEE-754表示的數(shù)字
      -(2的53次方 - 1) 到 (2的53次方 - 1)之間的整數(shù)(包含這兩個)。
      2的53次方+1就是非安全整數(shù)
    

6 String對象

屬性:

  • String.prototype: String原型對象
  • str.length:字符串的長度

方法

  • String.fromCharCode() 方法返回由指定的UTF-16代碼單元序列創(chuàng)建的字符串。

    String.fromCharCode(65, 66, 67);  // returns "ABC"
    String.fromCharCode(0x2014)       // returns "—"
    
  • String.fromCodePoint() 靜態(tài)方法返回使用指定的代碼點序列創(chuàng)建的字符串。

    String.fromCodePoint(42);       // "*"
    String.fromCodePoint(65, 90);   // "AZ"
    
    // String.fromCharCode() 方法不能單獨獲取在高代碼點位上的字符
    // 另一方面,下列的示例中,可以返回 4 字節(jié),也可以返回 2 字節(jié)的字符
    // (也就是說,它可以返回單獨的字符,使用長度 2 代替 1!) 
    console.log(String.fromCodePoint(0x2F804)); // 你
    console.log(String.fromCharCode(0x2F804));    // 特殊字符,此處無法顯示
    
  • str.charAt() 方法從一個字符串中返回指定的字符。

    var str = "Brave new world";
    
    str.charAt(0) // B
    str.charAt(6) // n
    
  • str.charCodeAt() 方法返回0到65535之間的整數(shù),表示給定索引處的UTF-16代碼單元

    var str = "Brave new world";
    
    str.charCodeAt(0) // 66
    str.charCodeAt(6) // 110
    
  • str.codePointAt() 方法返回 一個 Unicode 編碼點值的非負整數(shù)

    'ABC'.codePointAt(1);          // 66
    '\uD800\uDC00'.codePointAt(0); // 65536
    'XYZ'.codePointAt(42); // undefined
    
  • str.concat(str1, str2...) 方法將一個或多個字符串與原字符串連接合并,形成一個新的字符串并返回。

    var hello = "Hello, ";
    console.log(hello.concat("Kevin", " have a nice day.")); 
    
    // 輸出:Hello, Kevin have a nice day.
    
    此方法性能很差,使用賦值操作符+,+=代替concat方法
    
  • str.startsWith() 方法用來判斷當前字符串是否以另外一個給定的子字符串開頭,并根據(jù)判斷結(jié)果返回 truefalse。

    const str1 = 'Saturday night plans';
    
    console.log(str1.startsWith('Sat'));
    // expected output: true
    
    console.log(str1.startsWith('Sat', 3));
    // expected output: false
    
  • str.endsWith():方法用來判斷當前字符串是否是以另外一個給定的子字符串“結(jié)尾”的。

    var str = "To be, or not to be, that is the question.";
    
    alert( str.endsWith("question.") );  // true
    alert( str.endsWith("to be") );      // false
    alert( str.endsWith("to be", 19) );  // true
    
  • str.includes() 方法用于判斷一個字符串是否包含在另一個字符串中,根據(jù)情況返回 true 或 false。

    'Blue Whale'.includes('blue'); // returns false
    
  • str.indexOf(value, fromIndex):方法返回調(diào)用 String 對象中第一次出現(xiàn)的指定值的索引,開始在 fromIndex進行搜索。(區(qū)分大小寫)

    "Blue Whale".indexOf("Blue");     // returns  0
    "Blue Whale".indexOf("Blue");     // returns  0
    "Blue Whale".indexOf("Blute");    // returns -1
    "Blue Whale".indexOf("Whale", 0); // returns  5
    "Blue Whale".indexOf("Whale", 5); // returns  5
    
  • str.lastIndexOf()方法返回指定值在調(diào)用該方法的字符串中最后出現(xiàn)的位置,如果沒找到則返回 -1。從該字符串的后面向前查找,從 fromIndex 處開始。(區(qū)分大小寫)

    "canal".lastIndexOf("a")   // returns 3
    "canal".lastIndexOf("a",2) // returns 1
    "canal".lastIndexOf("a",0) // returns -1
    "canal".lastIndexOf("x")   // returns -1
    
  • str.match(regexp) 方法檢索返回一個字符串匹配正則表達式的的結(jié)果。

var str = 'I`m 16';
str.match(/\d+/); // ["16", index: 4, input: "I`m 16", groups: undefined]
  • str.matchAll() 方法返回一個包含所有匹配正則表達式及分組捕獲結(jié)果的迭代器。

    const regexp = RegExp('foo*','g');
    const str = 'table football, foosball';
    
    while ((matches = regexp.exec(str)) !== null) {
      console.log(`Found ${matches[0]}. Next starts at ${regexp.lastIndex}.`);
      // expected output: "Found foo. Next starts at 9."
      // expected output: "Found foo. Next starts at 19."
    } 
    

    使用matchAll更好的解決問題

    const regexp = RegExp('foo*','g'); 
    const str = 'table football, foosball';
    let matches = str.matchAll(regexp);
    
    for (const match of matches) {
      console.log(match);
    }
    // Array [ "foo" ]
    // Array [ "foo" ]
    
    // matches iterator is exhausted after the for..of iteration
    // Call matchAll again to create a new iterator
    matches = str.matchAll(regexp);
    
    Array.from(matches, m => m[0]);
    // Array [ "foo", "foo" ]
    
  • replace() 方法返回一個由替換值(replacement)替換一些或所有匹配的模式(pattern)后的新字符串。模式可以是一個字符串或者一個正則表達式,替換值可以是一個字符串或者一個每次匹配都要調(diào)用的回調(diào)函數(shù)。(原字符串不會改變)

    var p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
    
    var regex = /dog/gi;
    
    console.log(p.replace(regex, 'ferret'));
    // expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"
    
    console.log(p.replace('dog', 'monkey'));
    // expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"
    
    
  • str.search() 方法執(zhí)行正則表達式和 String 對象之間的一個搜索匹配。成功返回索引,失敗返回-1

    var paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';
    
    // any character that is not a word character or whitespace
    var regex = /[^\w\s]/g;
    
    console.log(paragraph.search(regex));
    // expected output: 43
    
    console.log(paragraph[paragraph.search(regex)]);
    // expected output: "."
    
  • str.slice(beginSlice[, endSlice]):提取一個字符串的一部分,并返回一新的字符串。

    var str = 'The morning is upon us.';
    str.slice(-3);     // returns 'us.'
    str.slice(-3, -1); // returns 'us'
    str.slice(0, -1);  // returns 'The morning is upon us'
    
  • str.substring(start, end) 方法返回一個字符串在開始索引到結(jié)束索引之間的一個子集, 或從開始索引直到字符串的末尾的一個子集。

    var anyString = "Mozilla";
    
    // 輸出 "Moz"
    console.log(anyString.substring(0,3));    // Moz
    console.log(anyString.substring(3,0));    // Moz
    console.log(anyString.substring(3,-3));   // Moz  -3轉(zhuǎn)為0
    
    注意:
    1. 不支持負數(shù)
    
  • str.split()方法使用指定的分隔符字符串將一個String對象分割成字符串數(shù)組,以將字符串分隔為子字符串,以確定每個拆分的位置。

    var str = 'The quick brown fox jumps over the lazy dog.';
    
    var words = str.split(' ');
    console.log(words[3]);
    // expected output: "fox"
    
    var chars = str.split('');
    console.log(chars[8]);
    // expected output: "k"
    
    var strCopy = str.split();
    console.log(strCopy);
    // expected output: Array ["The quick brown fox jumps over the lazy dog."]
    
    
  • str.padEnd(targetLength[, padString]) 方法會用一個字符串填充當前字符串(如果需要的話則重復(fù)填充),返回填充后達到指定長度的字符串。從當前字符串的末尾(右側(cè))開始填充。

    'abc'.padEnd(10);          // "abc       "
    'abc'.padEnd(10, "foo");   // "abcfoofoof"
    'abc'.padEnd(6, "123456"); // "abc123"
    'abc'.padEnd(1);           // "abc"
    
  • str.padStart(targetLength[, padString]) 方法用另一個字符串填充當前字符串(重復(fù),如果需要的話),以便產(chǎn)生的字符串達到給定的長度。填充從當前字符串的開始(左側(cè))應(yīng)用的。

    'abc'.padStart(10);         // "       abc"
    'abc'.padStart(10, "foo");  // "foofoofabc"
    'abc'.padStart(6,"123465"); // "123abc"
    'abc'.padStart(8, "0");     // "00000abc"
    'abc'.padStart(1);          // "abc"
    
  • str.repeat() 構(gòu)造并返回一個新字符串,該字符串包含被連接在一起的指定數(shù)量的字符串的副本。

    "abc".repeat(2)      // "abcabc"
    
    注意:
    1. 負數(shù)報錯RangeError
    2. 小數(shù)規(guī)整
    
  • str.toLowerCase()方法根據(jù)任何特定于語言環(huán)境的案例映射,返回調(diào)用字符串值轉(zhuǎn)換為小寫的值。

  • str.toUpperCase() 使用本地化(locale-specific)的大小寫映射規(guī)則將輸入的字符串轉(zhuǎn)化成大寫形式并返回結(jié)果字符串。

  • str.trim() 方法會從一個字符串的兩端刪除空白字符。在這個上下文中的空白字符是所有的空白字符 (space, tab, no-break space 等) 以及所有行終止符字符(如 LF,CR)。

  • str.trimRight() 從一個字符串的右端移除空白字符。

  • str.trimLeft() 從字符串的開頭刪除空格

    var orig = '   foo  ';
    console.log(orig.trim()); // 'foo'
    
    // 另一個.trim()例子,只從一邊刪除
    
    var orig = 'foo    ';
    console.log(orig.trim()); // 'foo'
    
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容