Giter Site home page Giter Site logo

utility's Introduction

一些常用的代码片段

将数字四舍五入到指定的小数位数

const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
round(1.005, 2);    // 1.01

返回两个或两个以上数字/数字数组中元素之和。

const sum = (...arr) => [].concat(...arr).reduce((acc, val) => acc + val, 0);
sum([1, 2, 3, 4]);  // 10

延迟异步函数的执行,返回一个pormise。

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
async function sleepyWork() {
    console.log("---------");
    await sleep(1000);
    console.log('我是1s后才开始输出的');
}
sleepyWork();

计算一个数组中某个值出现的次数 用Array.prototype.reduce()方法计算数组内的值进行递增

const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3

utility's People

Contributors

hatedme avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.