Js 常用函数学习记录

1 篇文章 0 订阅
本文详细介绍了JavaScript中的JSON对象的parse和stringify方法,Map数据结构的使用,以及Math对象中的随机数生成和数字格式化功能,同时涵盖了遍历数组和对象的不同方式。
摘要由CSDN通过智能技术生成

JS常用函数

JSON

  • JSON.parse()

    const json = '{"result":true, "count":42}';
    const obj = JSON.parse(json);
    console.log(obj.count);
    // Expected output: 42
    console.log(obj.result);
    // Expected output: true
    
    
  • JSON.stringify()

    console.log(JSON.stringify({ x: 5, y: 6 }));
    // Expected output: '{"x":5,"y":6}'
    
    console.log(
      JSON.stringify([new Number(3), new String('false'), new Boolean(false)]),
    );
    // Expected output: '[3,"false",false]'
    
    console.log(JSON.stringify({ x: [10, undefined, function () {}, Symbol('')] }));
    // Expected output: '{"x":[10,null,null,null]}'
    
    console.log(JSON.stringify(new Date(2006, 0, 2, 15, 4, 5)));
    // Expected output: '"2006-01-02T15:04:05.000Z"'
    

Map

  • Map() constructor

    const map1 = new Map();
    
    map1.set('a', 1);
    map1.set('b', 2);
    map1.set('c', 3);
    
    console.log(map1.get('a'));
    // Expected output: 1
    
    map1.set('a', 97);
    
    console.log(map1.get('a'));
    // Expected output: 97
    
    console.log(map1.size);
    // Expected output: 3
    
    map1.delete('b');
    
    console.log(map1.size);
    // Expected output: 2
    
    /*
    new Map()
    new Map(iterable)
    */
    const myMap = new Map([
      [1, "one"],
      [2, "two"],
      [3, "three"],
    ]);
    
  • Map.prototype@@iterator

    const map1 = new Map();
    
    map1.set('0', 'foo');
    map1.set(1, 'bar');
    
    const iterator1 = map1[Symbol.iterator]();
    
    for (const item of iterator1) {
      console.log(item);
    }
    // Expected output: Array ["0", "foo"]
    // Expected output: Array [1, "bar"]
    
    
  • Map.prototype.clear()

    const map1 = new Map();
    
    map1.set('bar', 'baz');
    map1.set(1, 'foo');
    
    console.log(map1.size);
    // Expected output: 2
    
    map1.clear();
    
    console.log(map1.size);
    // Expected output: 0
    
  • Map.prototype.delete()

    const map1 = new Map();
    map1.set('bar', 'foo');
    
    console.log(map1.delete('bar'));
    // Expected result: true
    // True indicates successful removal
    
    console.log(map1.has('bar'));
    // Expected result: false
    
    
  • Map.prototype.entries()

    /* 
    @brief: returns a new map iterator object that containsthe [key, value] pairs for each 
    element in this map in insertion order.
    */ 
    const map1 = new Map();
    
    map1.set('0', 'foo');
    map1.set(1, 'bar');
    
    const iterator1 = map1.entries();
    
    console.log(iterator1.next().value);
    // Expected output: Array ["0", "foo"]
    
    console.log(iterator1.next().value);
    // Expected output: Array [1, "bar"]
    
  • Map.prototype.forEach()

    function logMapElements(value, key, map) {
      console.log(`map[${key}] = ${value}`);
    }
    
    new Map([
      ['foo', 3],
      ['bar', {}],
      ['baz', undefined],
    ]).forEach(logMapElements);
    
    // Expected output: "m[foo] = 3"
    // Expected output: "m[bar] = [object Object]"
    // Expected output: "m[baz] = undefined"
    
  • Map.prototype.get()

    const map1 = new Map();
    map1.set('bar', 'foo');
    
    console.log(map1.get('bar'));
    // Expected output: "foo"
    
    console.log(map1.get('baz'));
    // Expected output: undefined
    
  • Map.groupBy()

    const inventory = [
      { name: 'asparagus', type: 'vegetables', quantity: 9 },
      { name: 'bananas', type: 'fruit', quantity: 5 },
      { name: 'goat', type: 'meat', quantity: 23 },
      { name: 'cherries', type: 'fruit', quantity: 12 },
      { name: 'fish', type: 'meat', quantity: 22 },
    ];
    
    const restock = { restock: true };
    const sufficient = { restock: false };
    const result = Map.groupBy(inventory, ({ quantity }) =>
      quantity < 6 ? restock : sufficient,
    );
    console.log(result.get(restock));
    // [{ name: "bananas", type: "fruit", quantity: 5 }]
    
  • Map.prototype.has()

    const map1 = new Map();
    map1.set('bar', 'foo');
    
    console.log(map1.has('bar'));
    // Expected output: true
    
    console.log(map1.has('baz'));
    // Expected output: false
    
  • Map.prototype.values()

    const map1 = new Map();
    
    map1.set('0', 'foo');
    map1.set(1, 'bar');
    
    const iterator1 = map1.values();
    
    console.log(iterator1.next().value);
    // Expected output: "foo"
    
    console.log(iterator1.next().value);
    // Expected output: "bar"
    
    
  • Map.prototype.keys()

    const map1 = new Map();
    
    map1.set('0', 'foo');
    map1.set(1, 'bar');
    
    const iterator1 = map1.keys();
    
    console.log(iterator1.next().value);
    // Expected output: "0"
    
    console.log(iterator1.next().value);
    // Expected output: 1
    
    
  • Map.prototype.set()

    const map1 = new Map();
    map1.set('bar', 'foo');
    
    console.log(map1.get('bar'));
    // Expected output: "foo"
    
    console.log(map1.get('baz'));
    // Expected output: undefined
    
    
  • Map.prototype.size

    const map1 = new Map();
    
    map1.set('a', 'alpha');
    map1.set('b', 'beta');
    map1.set('g', 'gamma');
    
    console.log(map1.size);
    // Expected output: 3
    

Math

  • Math.floor()
    /*
    @brief:rounds down and returns the largest integer 
    less than or equal to a given number.
    */
    console.log(Math.floor(5.95));
    // Expected output: 5
    
    console.log(Math.floor(5.05));
    // Expected output: 5
    
    console.log(Math.floor(5));
    // Expected output: 5
    
    console.log(Math.floor(-5.05));
    // Expected output: -6
    
  • Math.random()
    function getRandomInt(max) {
      return Math.floor(Math.random() * max);
    }
    
    console.log(getRandomInt(3));
    // Expected output: 0, 1 or 2
    
    console.log(getRandomInt(1));
    // Expected output: 0
    
    console.log(Math.random());
    // Expected output: a number from 0 to <1
    
    //TODO: Getting a random integer between two values
    function getRandomInt(min, max) {
      min = Math.ceil(min);
      max = Math.floor(max);
      return Math.floor(Math.random() * (max - min) + min); // The maximum is exclusive and the minimum is inclusive
    }
    

Number

  • Number.parseFloat()
    /*
    @brief: method parses an argument and returns a floating point number. 
    If a number cannot be parsed from the argument, it returns NaN.
    */
    function circumference(r) {
      if (Number.isNaN(Number.parseFloat(r))) {
        return 0;
      }
      return parseFloat(r) * 2.0 * Math.PI;
    }
    
    console.log(circumference('4.567abcdefgh'));
    // Expected output: 28.695307297889173
    
    console.log(circumference('abcdefgh'));
    // Expected output: 0
    
  • Number.parseInt()
    /*
    @brief:  method parses a string argument and
    returns an integer of the specified radix or base.
    */
    function roughScale(x, base) {
      const parsed = Number.parseInt(x, base);
      if (Number.isNaN(parsed)) {
        return 0;
      }
      return parsed * 100;
    }
    
    console.log(roughScale(' 0xF', 16));
    // Expected output: 1500
    
    console.log(roughScale('321', 2));
    // Expected output: 0
    
    
  • Number.prototype.toFixed()
    /*
    @brief: method of Number values formats 
    this number using fixed-point notatio
    */
    function financial(x) {
      return Number.parseFloat(x).toFixed(2);
    }
    
    console.log(financial(123.456));
    // Expected output: "123.46"
    
    console.log(financial(0.004));
    // Expected output: "0.00"
    
    console.log(financial('1.23e+5'));
    // Expected output: "123000.00"
    

js中几种遍历对象的方法

  1. 遍历数组:

    //q:使用for循环
    const array = [1, 2, 3, 4, 5];
    for (let i = 0; i < array.length; i++) {
        console.log(array[i]);
    }
    
    //2: 使用forEach 
    const array = [1, 2, 3, 4, 5];
    array.forEach(item => {
        console.log(item);
    });
    
  2. 遍历对象的属性

    //1.for...in 循环(遍历对象的可枚举属性)
    const obj = {a: 1, b: 2, c: 3};
    for (let key in obj) {
        console.log(key + ': ' + obj[key]);
    }
    
    //of 是对象本身,in是下标
    for (let key of obj) {
        console.log("key is: " + ': ' + key);
    }
    
    //2.Object.keys 方法结合 forEach(遍历对象的可枚举属性)
    const obj = {a: 1, b: 2, c: 3};
    Object.keys(obj).forEach(key => {
        console.log(key + ': ' + obj[key]);
    });
    
  3. 遍历 Map 对象:

    const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
    map.forEach((value, key) => {
        console.log(key + ': ' + value);
    });
    
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值