(10)内置对象-1

内置对象

我们平时忙于开发,很少有时间能够将文档看一遍。这样在很多时候,我们本可以一个原生方法能够实现的程序,却累的跟狗一样,写出来的程序还不定好使。为了减少重复造轮子的时间,将MDN的API结合自己的理解,归纳整理了下面的文档。MDN文档-JavaScript内置对象

1 Array对象

  • arr.length:获取数组元素的长度
var arr = ['Tom','John','Amy'];
arr.length    // 3
  • arr.concat():合并两个或多个数组
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():在数组末尾推入指定元素
var arr = ['Tom','John','Amy'];
arr.push('Jack');    // 4
arr        // ['Tom','John','Amy','Jack']
  • arr.pop():弹出并返回数组末尾元素
var arr = ['Tom','John','Amy'];
arr.pop();    // Amy
arr        // ['Tom','John']
  • arr.shift():弹出并返回数组第一个元素
var arr = ['Tom','John','Amy'];
arr.shift();    // Tom
arr        // ['John','Amy']
  • arr.unshift():在数组开头处添加指定元素
var arr = ['Tom','John','Amy'];
arr.unshift('Jack');    // 4
arr        // ['Jack',Tom','John','Amy']
  • arr.sort([函数:排序规则]):排序(默认采用字符串顺序排序,数字排序则需要通过自定义函数实现)
var arr = ['Tom','John','Amy'];
arr.sort();    // ["Amy", "John", "Tom"]
arr        // 改变原数组:["Amy", "John", "Tom"]
  • arr.reverse():数组元素顺序反转
var arr = ["Amy", "John", "Tom"];
arr.reverse()    // ['Tom', 'John', 'Amy']
  • arr.indexOf():获取指定元素在数组中的位置,不存在返回-1
var arr = ["Amy", "John", "Tom"];
arr.indexOf('John');    // 1
arr.indexOf('David');    // -1
  • arr.lastIndexOf():获取指定元素最后一次出现的位置,不存在返回-1
var arr = ["Amy", "John", "Tom", "David", "Tom", "Jeff"];
arr.lastIndexOf('Tom');    // 4
arr.lastIndexOf('James');    // -1
  • arr.slice(起始位置,结束位置):获取数组中指定的片段(不包含结束位置) - 复制数组
var arr = ["Amy", "John", "Tom", "David", "Jeff"];
arr.slice(2)    // ["Tom", "David", "Jeff"]
arr            // 原数组不发生变化,["Amy", "John", "Tom", "David", "Jeff"]

var arr = ["Amy", "John", "Tom", "David", "Jeff"];
arr.slice(2,4)    // 不包含结束位置 ["Tom", "David"]    
  • arr.splice(起始位置,长度):从数组中添加或删除元素。
var arr = ["Amy", "John", "Tom", "David", "Jeff"];
arr.splice(2)    // ["Tom", "David", "Jeff"]
arr            // 原数组发生变化,["Amy", "John"]

var arr = ["Amy", "John", "Tom", "David", "Jeff"];
arr.splice(2,2)    // ["Tom", "David"]
arr            // 原数组发生变化,["Amy", "John", "Jeff"]
  • arr.forEach(callback[, thisArg]): 对数组的每个元素执行一次提供的函数
var arr = ["Amy", "John", "Tom"];

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

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

注意:
1. forEach 遍历的范围在第一次调用 callback 前就会确定
2. 调用 forEach 后添加到数组中的项不会被 callback 访问到
3. 如果已经存在的值被改变,则传递给 callback 的值是 forEach 遍历到他们那一刻的值。
4. 已删除的项不会被遍历到
5. 如果已访问的元素在迭代时被删除了(例如使用 shift()),之后的元素将被跳过
6. forEach() 为每个数组元素执行callback函数;不像 map() 或者 reduce(),它总是返回 undefined 值,并且不可链式调用
7. forEach() 被调用时,不会改变原数组(即调用它的数组),即使传递的参数里的 callback被调用时可能会改变原数组
8. 没有办法中止或者跳出 forEach() 循环,除了抛出一个异常
    需要终止:
    1. 简单for循环
    2. for...of循环
    3. arr.every()
    4. arr.some()
    5. arr.find()
    6. arr.findIndex()
    7. 先使用filter再forEach也可以
9. 如果使用箭头函数,第二个thisArg参数忽略  
  • arr.every():检测数值元素的每个元素是否都符合条件。
var arr = [16,22,15,33,38,28];

// 要求:数组中的每个元素的值都必须大于18为true,其余都为假
arr.every(function(value){
    return value > 18;
})    // false
  • arr.some():检测数组元素中是否有元素符合指定条件。
var arr = [16,22,15,33,38,28];

// 要求:数组中的每个元素都小于18为true,其余都为真
arr.some(function(value){
    return value > 18;
})        // true

  • arr.map():通过指定函数处理数组的每个元素,并返回处理后的数组
var arr = [16,22,15,33,38,28];

// 要求:数组中的每个元素的值都必须大于18为true,其余都为假
arr.map(function(value){
    return value + 10;
})    // [26,32,25,43,48,38]
  • arr.filter():检测数值元素,并返回符合条件所有元素的数组。
var arr = [16,22,15,33,38,28];

// 要求:数组中超过18的元素都被筛选出来
arr.filter(function(value){
    return value > 18;
})    // [22,33,38,28]
  • Array.isArray():判断是否是一个数组
Array.isArray([1, 2, 3]);      // true
Array.isArray({foo: 123});    // false
Array.isArray("foobar");  // false
Array.isArray(undefined);  // false

与instanceof区别:
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):累加器和数组中的每个元素(从左到右)应用一个函数,将其减少为单个值
  • 对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值
  • array.reduceRight(callback,initnum):接受一个函数作为累加器(accumulator)和数组的每个值(从右到左)将其减少为单个值。
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array){
    return accumulator + currentValue;
});    // 最终结果:10

accumulator:计算值
currentValue: 当前值
currentIndex: 当前索引值
array: 处理的数组
callback 计算值 当前值 当前索引 处理的数组 返回值
第一次调用 0 1 1 [0, 1, 2, 3, 4] 1
第二次调用 1 2 2 [0, 1, 2, 3, 4] 3
第三次调用 3 3 3 [0, 1, 2, 3, 4] 6
第四次调用 6 4 4 [0, 1, 2, 3, 4] 10

可以完成的事情:

  1. 数组所有值求和(案例同上)

  2. 累加对象数组的值

    var initialValue = 0;
    var sum = [{x: 1}, {x:2}, {x:3}].reduce(
        (accumulator, currentValue) => accumulator + currentValue.x
        ,initialValue
    );
    
    console.log(sum) // logs 6
    
  1. 将二维数组转为一维数组

    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. 计算数组中每个元素出现的次数

    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绑定包含在对象数组中的数组

  5. // friends - 对象数组
    // 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. 数组去重

    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. 功能型函数管道

    // 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数组方法

  • arr.includes(查找元素, 起始位置):判断一个数组是否包含一个指定的值,如果是,酌情返回 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]]): 从一个类似数组或可迭代对象中创建一个新的数组实例。
arrayLike: 想要转换成数组的伪数组对象或可迭代对象
mapFn: 如果指定了该参数,新数组中的每个元素会执行该回调函数
thisArg: 可选参数,执行回调函数 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(): 创建一个具有可变数量参数的新数组实例,而不考虑参数的数量或类型
Array.of(7);       // [7] 
Array.of(1, 2, 3); // [1, 2, 3]

Array(7);          // [ , , , , , , ]
    注意:这是指一个有7个空位(empty)的数组,而不是由7个undefined组成的数组
Array(1, 2, 3);    // [1, 2, 3]
  • arr.copyWithin(target[, start[, end]]): 浅复制数组的一部分到同一数组中的另一个位置,并返回它,不会改变原数组的长度
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对象,该对象包含数组中每个索引的键/值对。
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]]):用一个固定值填充一个数组中从起始索引到终止索引内的全部元素。不包括终止索引。
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]):返回数组中满足提供的测试函数的第一个元素的值。否则返回 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]):返回数组中满足提供的测试函数的第一个元素的索引。否则返回 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):按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。(兼容性问题大)
// 扁平化嵌套数组
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 作为深度,展开任意深度的嵌套数组
arr3.flat(Infinity); 
// [1, 2, 3, 4, 5, 6]

// 扁平化与移除数组空项
var arr4 = [1, 2, , 4, 5];
arr4.flat();
// [1, 2, 4, 5]

替代方案1: 一层嵌套

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

// 反嵌套一层数组
arr1.reduce((acc, val) => acc.concat(val), []);// [1, 2, 3, 4]

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

替代方案2: 无限层嵌套

// 使用 reduce、concat 和递归无限反嵌套多层嵌套的数组
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 无限反嵌套多层嵌套数组
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 送回内层数组中的元素,不会改动原始输入 original input
      stack.push(...next);
    } else {
      res.push(next);
    }
  }
  // 使用 reverse 恢复原数组的顺序
  return res.reverse();
}
flatten(arr1);// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
  • arr.keys():返回一个包含数组中每个索引键的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 对象,该对象包含数组每个索引的值
const array1 = ['a', 'b', 'c'];
const iterator = array1.values();

for (const value of iterator) {
  console.log(value); // expected output: "a" "b" "c"
}
  • arr.flatMap(): 首先使用映射函数映射每个元素,然后将结果压缩成一个新数组。它与 map 和 深度值1的 flat 几乎相同,但 flatMap 通常在合并成一种方法的效率稍微高一些
var new_array = arr.flatMap(function callback(currentValue[, index[, array]]) {
    // 返回新数组的元素
}[, 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 中的函数返回的数组 “压平” 一层
arr1.flatMap(x => [[x * 2]]);
// [[2], [4], [6], [8]]

flatMap和flat区别:

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(): 其他类型转换为布尔值

注意:上面两种方式不能搞混
if (new Boolean(0)) {
    // 代码执行,对象为真
}

if (Boolean(0)) {
    // 代码不执行
}

自身属性:

Boolean.length:1
Boolean.prototype: Boolean构造函数的原型对象

继承的属性和方法

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作为构造函数使用,得到Date对象
2. 将Date作为常规函数调用,返回字符串,非Date对象
3. month从0-11,代表1-12月
4. 如果传入的值超过合理范围,相邻的数值会自动调整
    13月=>下一年的1月
    70分钟=>下一个小时的10分钟
5. 上面第四种方式,前两个参数必须传递,后面如果没有值,默认为1(天)或者0(时分秒毫秒)
6. UTC:格林威治时间,Locale:本地时间

属性:

  1. Date.prototype: 允许为Date对象添加属性
  2. Date.length: 7

方法:

  1. Date.now(): 返回自 1970-1-1 00:00:00 UTC(世界标准时间)至今所经过的毫秒数。
  2. Date.parse(): 解析一个表示日期的字符串,并返回从 1970-1-1 00:00:00 所经过的毫秒数。
  3. Date.UTC(): 接受和构造函数最长形式的参数相同的参数(从2到7),并返回从 1970-01-01 00:00:00 UTC 开始所经过的毫秒数。

所有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(): 获取小时数

  5. d.getMilliseconds()/d.getUTCMilliseconds(): 获取毫秒数

  6. d.getMinutes()/d.getUTCMinutes(): 获取分钟数

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

  8. d.getSeconds()/d.getUTCSeconds: 获取毫秒数(0-59)

  9. d.getTime(): 返回从1970-1-1 00:00:00 UTC(协调世界时)到该日期经过的毫秒数,对于1970-1-1 00:00:00 UTC之前的时间返回负值。

上述所有的get方法都对应他们的set方法

  1. d.setDate(): 设置每月的第几天(1-31)
  2. d.setFullYear(): 设置指定年份
  3. d.setHours(): 设置小时数
  4. d.setMilliseconds(): 设置毫秒数
  5. d.setMinutes(): 设置分钟数
  6. d.setMonth(): 设置月份(0-11)
  7. d.setSeconds(): 设置毫秒数(0-59)
  8. d.setTime(): 通过指定从 1970-1-1 00:00:00 UTC 开始经过的毫秒数来设置日期对象的时间,对于早于 1970-1-1 00:00:00 UTC的时间可使用负值。

其他方法:

  1. d.toDateString():返回日期部分字符串
  2. d.toLocaleDateString():返回一个表示该日期对象日期部分的字符串,该字符串格式与系统设置的地区关联。
  3. d.toLocaleTimeString():返回一个表示该日期对象时间部分的字符串,该字符串格式与系统设置的地区关联。
  4. d.toLocaleString():返回一个表示该日期对象的字符串,该字符串格式与系统设置的地区关联。
  5. d.toString():返回一个表示该日期对象的字符串。
  6. d.valueOf():返回一个日期对象的原始值(时间戳)

4 Math对象

Math不是构造器,所有的属性和额方法都是静态的。

属性

  • Math.PI:圆周率(3.15159)
  • Math.E:欧拉常数
  • Math.LN2:2的自然对数
  • Math.LN10:10的自然对数
  • Math.LOG2E:以2为底E的对数
  • Math.LOG10E:以10为底E的对数
  • 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():获取随机数

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 弧度之间的数值来返回 x 的反正切值/反双曲正切值/返回 y/x 的反正切值.
  • Math.asin()
  • Math.acos()
  • Math.atan()
  • Math.tan2()
三角函数是以弧度返回值的,通过除法Math.PI/180把弧度转换为角度,也可以通过其他方法转换。
  • Math.cbrt(): 返回x的立方根
  • Math.log(): 返回一个数的自然对数
  • Math.log1p(): 返回 1 加上一个数字的的自然对数
  • Math.log10(): 返回以10为底数的x的对数。
  • Math.log2(): 返回以2为底数的x的对数。
  • Math.pow(): 返回x的y次幂.
  • Math.round(): 四舍五入的整数
  • Math.sign(): 返回x的符号函数, 判定x是正数,负数还是0.
  • Math.sqrt(): 平方根

5 Number对象

主要功能:用来执行类型转换。

属性:

  • 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:最大的安全整数(2的53次方-1)

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

  • Number.MAX_VALUE:能表示的最大正数

  • Number.MIN_VALUE:能表示的最小正数即最接近 0 的正数 (实际上不会变成 0)

  • Number.NaN:特殊的“非数字”值

  • Number.NEGATIVE_INFINITY:属性表示负无穷大

  • Number.POSITIVE_INFINITY 属性表示正无穷大

方法:

  • Number.isFinite() 方法用来检测传入的参数是否是一个有穷数(finite number)。

  • Number.isInteger() 方法用来判断给定的参数是否为整数。

  • Number.isNaN() 方法确定传递的值是否为 NaN和其类型是 Number。它是原始的全局isNaN()的更强大的版本。

  • Number.isSafeInteger() 方法用来判断传入的参数值是否是一个“安全整数”(safe integer)。一个安全整数是一个符合下面条件的整数:

  • Number.parseFloat() 方法可以把一个字符串解析成浮点数。

  • Number.parseInt() 方法依据指定基数 [ 参数 radix 的值],把字符串 [ 参数 string 的值] 解析成整数。

  • num.toExponential() 方法以指数表示法返回该数值字符串表示形式。

  • num.toFixed()方法使用定点表示法来格式化一个数。

  • num.toPrecision()方法以指定的精度返回该数值对象的字符串表示。

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

  • num.valueOf() 方法返回一个被 Number 对象包装的原始值。

    注意:
    1. 安全整数:IEEE-754表示的数字
      -(2的53次方 - 1) 到 (2的53次方 - 1)之间的整数(包含这两个)。
      2的53次方+1就是非安全整数
    

6 String对象

属性:

  • String.prototype: String原型对象
  • str.length:字符串的长度

方法

  • String.fromCharCode() 方法返回由指定的UTF-16代码单元序列创建的字符串。

    String.fromCharCode(65, 66, 67);  // returns "ABC"
    String.fromCharCode(0x2014)       // returns "—"
    
  • String.fromCodePoint() 静态方法返回使用指定的代码点序列创建的字符串。

    String.fromCodePoint(42);       // "*"
    String.fromCodePoint(65, 90);   // "AZ"
    
    // String.fromCharCode() 方法不能单独获取在高代码点位上的字符
    // 另一方面,下列的示例中,可以返回 4 字节,也可以返回 2 字节的字符
    // (也就是说,它可以返回单独的字符,使用长度 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之间的整数,表示给定索引处的UTF-16代码单元

    var str = "Brave new world";
    
    str.charCodeAt(0) // 66
    str.charCodeAt(6) // 110
    
  • str.codePointAt() 方法返回 一个 Unicode 编码点值的非负整数

    '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() 方法用来判断当前字符串是否以另外一个给定的子字符串开头,并根据判断结果返回 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():方法用来判断当前字符串是否是以另外一个给定的子字符串“结尾”的。

    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() 方法用于判断一个字符串是否包含在另一个字符串中,根据情况返回 true 或 false。

    'Blue Whale'.includes('blue'); // returns false
    
  • str.indexOf(value, fromIndex):方法返回调用 String 对象中第一次出现的指定值的索引,开始在 fromIndex进行搜索。(区分大小写)

    "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()方法返回指定值在调用该方法的字符串中最后出现的位置,如果没找到则返回 -1。从该字符串的后面向前查找,从 fromIndex 处开始。(区分大小写)

    "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) 方法检索返回一个字符串匹配正则表达式的的结果。

var str = 'I`m 16';
str.match(/\d+/); // ["16", index: 4, input: "I`m 16", groups: undefined]
  • str.matchAll() 方法返回一个包含所有匹配正则表达式及分组捕获结果的迭代器。

    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)后的新字符串。模式可以是一个字符串或者一个正则表达式,替换值可以是一个字符串或者一个每次匹配都要调用的回调函数。(原字符串不会改变)

    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() 方法执行正则表达式和 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) 方法返回一个字符串在开始索引到结束索引之间的一个子集, 或从开始索引直到字符串的末尾的一个子集。

    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转为0
    
    注意:
    1. 不支持负数
    
  • str.split()方法使用指定的分隔符字符串将一个String对象分割成字符串数组,以将字符串分隔为子字符串,以确定每个拆分的位置。

    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]) 方法会用一个字符串填充当前字符串(如果需要的话则重复填充),返回填充后达到指定长度的字符串。从当前字符串的末尾(右侧)开始填充。

    'abc'.padEnd(10);          // "abc       "
    'abc'.padEnd(10, "foo");   // "abcfoofoof"
    'abc'.padEnd(6, "123456"); // "abc123"
    'abc'.padEnd(1);           // "abc"
    
  • str.padStart(targetLength[, padString]) 方法用另一个字符串填充当前字符串(重复,如果需要的话),以便产生的字符串达到给定的长度。填充从当前字符串的开始(左侧)应用的。

    '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() 构造并返回一个新字符串,该字符串包含被连接在一起的指定数量的字符串的副本。

    "abc".repeat(2)      // "abcabc"
    
    注意:
    1. 负数报错RangeError
    2. 小数规整
    
  • str.toLowerCase()方法根据任何特定于语言环境的案例映射,返回调用字符串值转换为小写的值。

  • str.toUpperCase() 使用本地化(locale-specific)的大小写映射规则将输入的字符串转化成大写形式并返回结果字符串。

  • 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'
    
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,830评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,992评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,875评论 0 331
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,837评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,734评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,091评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,550评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,217评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,368评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,298评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,350评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,027评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,623评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,706评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,940评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,349评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,936评论 2 341