Lambda和Linq三表连接查询加分组

三表连接查询加分组的方法

方法一:Lambda

方法二:Linq

数据库事例:

效果图:



.NetCore JWT认证

1、创建.net core web api项目:

Create a Web API with ASP.NET Core and Visual Studio

按照上面链接创建项目。

2、添加JWT(Bearer Token)认证

  • 在项目的Startup.cs文件中的ConfigureServices方法添加以下代码添加并配置JWT认证:
            //添加jwt验证:services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options => {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,//是否验证Issuer
            ValidateAudience = true,//是否验证Audience
            ValidateLifetime = true,//是否验证失效时间
            ValidateIssuerSigningKey = true,//是否验证SecurityKey
            ValidAudience = Configuration["audience"],//Audience
            ValidIssuer = Configuration["issuer"],//Issuer,这两项和签发jwt的设置一致
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["SecurityKey"]))//拿到SecurityKey
        };
     });

其中 Configuration[“audience”]、Configuration[“issuer”]、Configuration[“SecurityKey”]为读取项目中appsettings.json文件中的自定义字符串。

appsettings.json文件:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "SecurityKey": "dd%88*377f6d&f£$£$#$%#$%#$FF33fssDG^!3",
  "issuer": "guetServer",
  "audience": "guetClient"
}
  • 在项目的Startup.cs文件中的Configure方法添加以下代码配置授权:
app.UseAuthentication();//配置授权
  • 签发JWT

首先自定义API连接返回的数据类型在项目的Models文件夹添加RestfulData类,新建类文件,对应命名空间里面定义三个类,代码如下:

    public class RestfulData
    {
        /// <summary>
        /// <![CDATA[错误码]]>
        /// </summary>
        public int code { get; set; }

        /// <summary>
        ///<![CDATA[消息]]>
        /// </summary>
        public string message { get; set; }

        /// <summary>
        /// <![CDATA[相关的链接帮助地址]]>
        /// </summary>
        public string url { get; set; }

    }

    /// <summary>
    ///
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class RestfulData<T> : RestfulData
    {
        /// <summary>
        /// <![CDATA[数据]]>
        /// </summary>
        public virtual T data { get; set; }
    }

    /// <summary>
    /// <![CDATA[返回数组]]>
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class RestfulArray<T> : RestfulData<IEnumerable<T>>
    {

    }

在项目中Models文件夹新建TokenObj类,代码如下

    public class TokenObj
    {
        public string token { get; set; }//token内容

        public long expires { get; set; }//过期时间
    }

做好以上准备之后在项目的Controllers文件夹里面新建一个API控制器类,如下图:

命名为OAuthController.cs。

将里面的方法全部删除,添加入以下代码

        private readonly IConfiguration _configuration;
  
        public OAuthController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        /// <summary>
        /// <![CDATA[获取访问令牌]]>
        /// </summary>
        /// <param name="user"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<RestfulData<TokenObj>> Token(string user, string password)//同步方法
        {
            var result = new RestfulData<TokenObj>();
            try
            {
                if (string.IsNullOrEmpty(user)) throw new ArgumentNullException("user", "用户名不能为空!");
                if (string.IsNullOrEmpty(password)) throw new ArgumentNullException("password", "密码不能为空!");

                //验证数据库用户名和密码
                //var userInfo = await _UserService.CheckUserAndPassword(user,  password);
                var claims = new Claim[]
                {
                    new Claim(ClaimTypes.Name,user),
                    new Claim(ClaimTypes.NameIdentifier,password),
                };

                var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(_configuration["SecurityKey"]));
                var expires = DateTime.Now.AddDays(30);//
                var token = new JwtSecurityToken(
                            issuer: _configuration["issuer"],
                            audience: _configuration["audience"],
                            claims: claims,
                            notBefore: DateTime.Now,
                            expires: expires,
                            signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));

                //生成Token
                string jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
                result.code = 200;
                result.data = new TokenObj() { token = jwtToken, expires = expires.ToFileTimeUtc() };
                result.message = "授权成功!";
                return result;
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.code = 400;
                // logger.Error("获取访问令牌时发生错误!", ex);
                return result;
            }
        }

下面添加Swagger UI并验证JWT认证。

3、添加Swashbuckle

Get started with Swashbuckle and ASP.NET Core

按照上面链接添加Swagger UI

  • 在Swagger中添加JWT认证功能

在startup.cs文件中的ConfigureServices方法中的services.AddSwaggerGen配置末尾添加以下代码

                c.AddSecurityDefinition("Bearer", 
                    new ApiKeyScheme {
                        In = "header",
                        Description = "请输入OAuth接口返回的Token,前置Bearer。示例:Bearer {Roken}",
                        Name = "Authorization",
                        Type = "apiKey"
                    });
                c.AddSecurityRequirement(
                    new Dictionary<string, IEnumerable<string>>
                    {
                        { "Bearer",
                          Enumerable.Empty<string>()
                        },
                    });

4、调试

在项目内置的ValuesController中给Get方法添加[Authorize]标签,如下图所示:

调试项目,进入Swagger UI页面,url为http://localhost:<port>/swagger进行调试。

直接请求GET  /api/Values

点击Try it out,再点Execute可见Server response的code是401,未授权: (Unauthorized)

我们尝试OAuth接口获取Token,user password随便输入,可以看到返回的数据有一个token。我们将它复制备用。

点击页面上端的Authorize按钮,按如下图格式输入我们刚刚复制的token,前面带有Bearer,与复制的token间隔一个空格。

再点击Authorize按钮,关闭对话框,然后再去尝试GET  /api/Values接口吧!

返回结果正确,DONE!!!!

生成的token超长,尚未知道如何刷新token。

 

CSS实现垂直居中的常用方法

在前端开发过程中,盒子居中是常常用到的。其中 ,居中又可以分为水平居中和垂直居中。水平居中是比较容易的,直接设置元素的margin: 0 auto就可以实现。但是垂直居中相对来说是比较复杂一些的。下面我们一起来讨论一下实现垂直居中的方法。

首先,定义一个需要垂直居中的div元素,他的宽度和高度均为300px,背景色为橙色。代码如下: 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
    <style>
        .content {
            width: 300px;
            height: 300px;
            background: orange;
        }
    </style>
</head>
<body>
    <div class="content"></div>
</body>
</html>

    

效果如下:      
       我们需要使得这个橙色的div居中,到底该怎么办呢?首先我们实现水平居中,上面已经提到过了,可以通过设置margin: 0 auto实现水平居中,代码如下:  

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
    <style>
        .content {
            width: 300px;
            height: 300px;
            background: orange;
            margin: 0 auto;
        }
    </style>
</head>
<body>
    <div class="content"></div>
</body>
</html>

 

    效果如下:  
      很好,已经实现水平居中了!接下来该打大boss了——实现垂直居中。不过,在这之前,我们先要设置div元素的祖先元素html和body的高度为100%(因为他们默认是为0的),并且清除默认样式,即把margin和padding设置为0(如果不清除默认样式的话,浏览器就会出现滚动条,聪明的亲,自己想想问什么)。  

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
    <style>
        html, body {
            width: 100%;
            height: 100%;
            margin: 0; 
            padding: 0;
        }
        .content {
            width: 300px;
            height: 300px;
            background: orange;
            margin: 0 auto; /*水平居中*/
        }
    </style>
</head>
<body>
    <div class="content"></div>
</body>
</html>

   

 接下来,需要做的事情就是要让div往下移动了。我们都知道top属性可以使得元素向下偏移的。但是,由于默认情况下,由于position的值为static(静止的、不可以移动的),元素在文档流里是从上往下、从左到右紧密的布局的,我们不可以直接通过top、left等属性改变它的偏移。所以,想要移动元素的位置,就要把position设置为不是static的其他值,如relative,absolute,fixed等。然后,就可以通过top、bottom、right、left等属性使它在文档中发生位置偏移(注意,relative是不会使元素脱离文档流的,absolute和fixed则会!也就是说,relative会占据着移动之前的位置,但是absolute和fixed就不会)。设置了position: relative后的代码如下:  

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
    <style>
        html, body {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
        }
        .content {
            width: 300px;
            height: 300px;
            background: orange;
            margin: 0 auto; /*水平居中*/
            position: relative; /*设置position属性*/
        }
    </style>
</head>
<body>
    <div class="content"></div>
</body>
</html>

 

    我们刷新一下页面,发现跟之前是没有任何变化的,因为,我们仅仅是使设置了元素的position=relative而已,但是还没开始移动他的垂直偏移。好,下面我们就让它偏移吧!垂直偏移需要用到top属性,它的值可以是具体的像素,也可以是百分数。因为我们现在不知道父元素(即body)的具体高度,所以,是不可以通过具体像素来偏移的,而应该用百分数。既然是要让它居中嘛!好,那么我们就让它的值为50%不就行了吗?问题真的那么简单,我们来试一下,就设置50%试一下:  

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
    <style>
        html,body {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
        }
        .content {
            width: 300px;
            height: 300px;
            background: orange;
            margin: 0 auto; /*水平居中*/
            position: relative; /*脱离文档流*/
            top: 50%; /*偏移*/
        }
    </style>
</head>
<body>
    <div class="content"></div>
</body>
</html>

 

    效果如下图所示:  
        div垂直方向上面并没有居中。明显是偏下了。下面,我们在浏览器中间画一条红线用来参考,如下图:  
      通过观察上图,只要让div的中心移动到红线的位置,那么整个div就居中了。那怎么让它中心移动到红线处呢?从图中可以观察到,从div的中心到红线的距离是div自身高度的一半。这时候,我们可以使用通过margin-top属性来设置,因为div的自身高度是300,所以,需要设置他的margin-top值为-150。为什么是要设置成负数的呢?因为正数是向下偏移,我们是希望div向上偏移,所以应该是负数,如下:  

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
    <style>
        html,body {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
        }
        .content {
            width: 300px;
            height: 300px;
            background: orange;
            margin: 0 auto; /*水平居中*/
            position: relative;
            top: 50%; /*偏移*/
            margin-top: -150px; 
        }
    </style>
</head>
<body>
    <div class="content"></div>
</body>
</html>

 

效果如下:  
      确实已经居中了。好兴奋!有木有?!       除了可以使用margin-top把div往上偏移之外,CSS3的transform属性也可以实现这个功能,通过设置div的transform: translateY(-50%),意思是使得div向上平移(translate)自身高度的一半(50%)。如下:  

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
    <style>
        html,body {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
        }
        .content {
            width: 300px;
            height: 300px;
            background: orange;
            margin: 0 auto; /*水平居中*/
            position: relative;
            top: 50%; /*偏移*/
            transform: translateY(-50%);
        }
    </style>
</head>
<body>
    <div class="content"></div>
</body>
</html>

 

    效果如下:  
      上面的两种方法,我们都是基于设置div的top值为50%之后,再进行调整垂偏移量来实现居中的。如果使用CSS3的弹性布局(flex)的话,问题就会变得容易多了。使用CSS3的弹性布局很简单,只要设置父元素(这里是指body)的display的值为flex即可。具体代码如下,对代码不做过多的解释,如果想了解弹性布局的可以看阮一峰老师的博客
http://www.ruanyifeng.com/blog/2015/07/flex-grammar.html:  

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
    <style>
        html,body {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
        }
    
        body {
            display: flex;
            align-items: center; /*定义body的元素垂直居中*/
            justify-content: center; /*定义body的里的元素水平居中*/
        }
        .content {
            width: 300px;
            height: 300px;
            background: orange;        
        }
    </style>
</head>
<body>
    <div class="content"></div>
</body>
</html>

 

    效果:  
      除了上面3中方法之外,当然可能还存在许多的可以实现垂直居中的方法。比如可以将父容器设置为display:table ,然后将子元素也就是要垂直居中显示的元素设置为 display:table-cell 。但是,这是不值得推荐的,因为会破坏整体的布局。如果用table布局,那么为什么不直接使用table标签了?那不更加方便吗?     关于CSS实现垂直居中的方法,就写这么多了。如果,发现哪里写的不对的或者有更好的方法的,请在评论提出来,这样大家可以一起讨论、共同进步!  
2018年8月24日更新 最近,看了张鑫旭老师的《CSS世界》一书,不采用CSS3,而是使用了CSS2的vertical-align,通过一些黑科技手段实现了垂直居中,有兴趣的同学可以研究一下。具体实现如下: 假设类名是.dialog,则 HTML 如下:

<div class="container">
  <div class="dialog">
  </div>
</div>

核心 CSS 代码如下:

.container {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background-color: rgba(0,0,0,.5);
    text-align: center;
    font-size: 0;
    white-space: nowrap;
    overflow: auto;
}

.container:after {
    content: '';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}

.dialog {
    display: inline-block;
    vertical-align: middle;
    text-align: left;
    font-size: 14px;
    white-space: normal;
}

 

 

JS实现几分钟前,刚刚

function getDateDiff(dateTimeStamp) {
  var result;
  var minute = 1000 * 60;
  var hour = minute * 60;
  var day = hour * 24;
  var halfamonth = day * 15;
  var month = day * 30;
  var now = new Date().getTime();
  var diffValue = now - new Date(dateTimeStamp).getTime();
  if (diffValue < 0) {
    return;
  }
  var monthC = diffValue / month;
  var weekC = diffValue / (7 * day);
  var dayC = diffValue / day;
  var hourC = diffValue / hour;
  var minC = diffValue / minute;
  if (monthC >= 1) {
    if (monthC <= 12) result = "" + parseInt(monthC) + "月前";
    else {
      result = "" + parseInt(monthC / 12) + "年前";
    }
  } else if (weekC >= 1) {
    result = "" + parseInt(weekC) + "周前";
  } else if (dayC >= 1) {
    result = "" + parseInt(dayC) + "天前";
  } else if (hourC >= 1) {
    result = "" + parseInt(hourC) + "小时前";
  } else if (minC >= 1) {
    result = "" + parseInt(minC) + "分钟前";
  } else {
    result = "刚刚";
  }
  return result;
}

使用JavaScript的一些小技巧

任何一门技术在实际中都会有一些属于自己的小技巧。同样的,在使用JavaScript时也有一些自己的小技巧,只不过很多时候有可能容易被大家忽略。而在互联网上,时不时的有很多同行朋友会总结(或收集)一些这方面的小技巧。作为一位JavaScript的菜鸟级的同学,更应该要留意这些小技巧,因为这些小技巧可以在实际业务的开发中帮助我们解决问题,而且会很容易的解决问题。在这篇文章中,会整理一些大家熟悉或不熟悉的有关于JavaScript的小技巧。

数组

先来看使用数组中常用的一些小技巧。

数组去重

ES6提供了几种简洁的数组去重的方法,但该方法并不适合处理非基本类型的数组。对于基本类型的数组去重,可以使用... new Set()来过滤掉数组中重复的值,创建一个只有唯一值的新数组。

const array = [1, 1, 2, 3, 5, 5, 1]
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); 

> Result:(4) [1, 2, 3, 5]

这是ES6中的新特性,在ES6之前,要实现同样的效果,我们需要使用更多的代码。该技巧适用于包含基本类型的数组:undefinednullbooleanstringnumber。如果数组中包含了一个object,function或其他数组,那就需要使用另一种方法。

除了上面的方法之外,还可以使用Array.from(new Set())来实现:

const array = [1, 1, 2, 3, 5, 5, 1]
Array.from(new Set(array))
> Result:(4) [1, 2, 3, 5]

另外,还可以使用Array.filterindexOf()来实现:

const array = [1, 1, 2, 3, 5, 5, 1]
array.filter((arr, index) => array.indexOf(arr) === index)

> Result:(4) [1, 2, 3, 5]

注意,indexOf()方法将返回数组中第一个出现的数组项。这就是为什么我们可以在每次迭代中将indexOf()方法返回的索引与当索索引进行比较,以确定当前项是否重复。

确保数组的长度

在处理网格结构时,如果原始数据每行的长度不相等,就需要重新创建该数据。为了确保每行的数据长度相等,可以使用Array.fill来处理:

let array = Array(5).fill('');
console.log(array); 

> Result: (5) ["", "", "", "", ""]

数组映射

不使用Array.map来映射数组值的方法。

const array = [
    {
        name: '大漠',
        email: 'w3cplus@hotmail.com'
    },
    {
        name: 'Airen',
        email: 'airen@gmail.com'
    }
]

const name = Array.from(array, ({ name }) => name)

> Result: (2) ["大漠", "Airen"]

数组截断

如果你想从数组末尾删除值(删除数组中的最后一项),有比使用splice()更快的替代方法。

例如,你知道原始数组的大小,可以重新定义数组的length属性的值,就可以实现从数组末尾删除值:

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(array.length)
> Result: 10

array.length = 4
console.log(array)
> Result: (4) [0, 1, 2, 3]

这是一个特别简洁的解决方案。但是,slice()方法运行更快,性能更好:

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array = array.slice(0, 4);

console.log(array); 
> Result: [0, 1, 2, 3]

过滤掉数组中的falsy值

如果你想过滤数组中的falsy值,比如0undefinednullfalse,那么可以通过mapfilter方法实现:

const array = [0, 1, '0', '1', '大漠', 'w3cplus.com', undefined, true, false, null, 'undefined', 'null', NaN, 'NaN', '1' + 0]
array.map(item => {
    return item
}).filter(Boolean)

> Result: (10) [1, "0", "1", "大漠", "w3cplus.com", true, "undefined", "null", "NaN", "10"]

获取数组的最后一项

数组的slice()取值为正值时,从数组的开始处截取数组的项,如果取值为负整数时,可以从数组末属开始获取数组项。

let array = [1, 2, 3, 4, 5, 6, 7]

const firstArrayVal = array.slice(0, 1)
> Result: [1]

const lastArrayVal = array.slice(-1)
> Result: [7]

console.log(array.slice(1))
> Result: (6) [2, 3, 4, 5, 6, 7]

console.log(array.slice(array.length))
> Result: []

正如上面示例所示,使用array.slice(-1)获取数组的最后一项,除此之外还可以使用下面的方式来获取数组的最后一项:

console.log(array.slice(array.length - 1))
> Result: [7]

过滤并排序字符串列表

你可能有一个很多名字组成的列表,需要过滤掉重复的名字并按字母表将其排序。

在我们的例子里准备用不同版本语言的JavaScript 保留字的列表,但是你能发现,有很多重复的关键字而且它们并没有按字母表顺序排列。所以这是一个完美的字符串列表(数组)来测试我们的JavaScript小知识。

var keywords = ['do', 'if', 'in', 'for', 'new', 'try', 'var', 'case', 'else', 'enum', 'null', 'this', 'true', 'void', 'with', 'break', 'catch', 'class', 'const', 'false', 'super', 'throw', 'while', 'delete', 'export', 'import', 'return', 'switch', 'typeof', 'default', 'extends', 'finally', 'continue', 'debugger', 'function', 'do', 'if', 'in', 'for', 'int', 'new', 'try', 'var', 'byte', 'case', 'char', 'else', 'enum', 'goto', 'long', 'null', 'this', 'true', 'void', 'with', 'break', 'catch', 'class', 'const', 'false', 'final', 'float', 'short', 'super', 'throw', 'while', 'delete', 'double', 'export', 'import', 'native', 'public', 'return', 'static', 'switch', 'throws', 'typeof', 'boolean', 'default', 'extends', 'finally', 'package', 'private', 'abstract', 'continue', 'debugger', 'function', 'volatile', 'interface', 'protected', 'transient', 'implements', 'instanceof', 'synchronized', 'do', 'if', 'in', 'for', 'let', 'new', 'try', 'var', 'case', 'else', 'enum', 'eval', 'null', 'this', 'true', 'void', 'with', 'break', 'catch', 'class', 'const', 'false', 'super', 'throw', 'while', 'yield', 'delete', 'export', 'import', 'public', 'return', 'static', 'switch', 'typeof', 'default', 'extends', 'finally', 'package', 'private', 'continue', 'debugger', 'function', 'arguments', 'interface', 'protected', 'implements', 'instanceof', 'do', 'if', 'in', 'for', 'let', 'new', 'try', 'var', 'case', 'else', 'enum', 'eval', 'null', 'this', 'true', 'void', 'with', 'await', 'break', 'catch', 'class', 'const', 'false', 'super', 'throw', 'while', 'yield', 'delete', 'export', 'import', 'public', 'return', 'static', 'switch', 'typeof', 'default', 'extends', 'finally', 'package', 'private', 'continue', 'debugger', 'function', 'arguments', 'interface', 'protected', 'implements', 'instanceof'];

因为我们不想改变我们的原始列表,所以我们准备用高阶函数叫做filter,它将基于我们传递的回调方法返回一个新的过滤后的数组。回调方法将比较当前关键字在原始列表里的索引和新列表中的索引,仅当索引匹配时将当前关键字push到新数组。

最后我们准备使用sort方法排序过滤后的列表,sort只接受一个比较方法作为参数,并返回按字母表排序后的列表。

在ES6下使用箭头函数看起来更简单:

const filteredAndSortedKeywords = keywords
    .filter((keyword, index) => keywords.lastIndexOf(keyword) === index)
    .sort((a, b) => a < b ? -1 : 1);

这是最后过滤和排序后的JavaScript保留字列表:

console.log(filteredAndSortedKeywords);

> Result: ['abstract', 'arguments', 'await', 'boolean', 'break', 'byte', 'case', 'catch', 'char', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do', 'double', 'else', 'enum', 'eval', 'export', 'extends', 'false', 'final', 'finally', 'float', 'for', 'function', 'goto', 'if', 'implements', 'import', 'in', 'instanceof', 'int', 'interface', 'let', 'long', 'native', 'new', 'null', 'package', 'private', 'protected', 'public', 'return', 'short', 'static', 'super', 'switch', 'synchronized', 'this', 'throw', 'throws', 'transient', 'true', 'try', 'typeof', 'var', 'void', 'volatile', 'while', 'with', 'yield']

清空数组

如果你定义了一个数组,然后你想清空它。 通常,你会这样做:

let array = [1, 2, 3, 4];
function emptyArray() {
    array = [];
}
emptyArray();

但是,这有一个效率更高的方法来清空数组。 你可以这样写:

let array = [1, 2, 3, 4];
function emptyArray() {
    array.length = 0;
}
emptyArray();

拍平多维数组

使用...运算符,将多维数组拍平:

const arr = [1, [2, '大漠'], 3, ['blog', '1', 2, 3]]
const flatArray = [].concat(...arr)

console.log(flatArray)
> Result: (8) [1, 2, "大漠", 3, "blog", "1", 2, 3]

不过上面的方法只适用于二维数组。不过通过递归调用,可以使用它适用于二维以下的数组:

function flattenArray(arr) {  
    const flattened = [].concat(...arr);  
    return flattened.some(item => Array.isArray(item)) ? flattenArray(flattened) : flattened;
}

const array = [1, [2, '大漠'], 3, [['blog', '1'], 2, 3]]
const flatArr = flattenArray(array)
console.log(flatArr)
> Result: (8) [1, 2, "大漠", 3, "blog", "1", 2, 3]

从数组中获取最大值和最小值

可以使用Math.maxMath.min取出数组中的最大小值和最小值:

const numbers = [15, 80, -9, 90, -99]
const maxInNumbers = Math.max.apply(Math, numbers)
const minInNumbers = Math.min.apply(Math, numbers)

console.log(maxInNumbers)
> Result: 90

console.log(minInNumbers)
> Result: -99

另外还可以使用ES6的...运算符来完成:

const numbers = [1, 2, 3, 4];
Math.max(...numbers) 
> Result: 4

Math.min(...numbers) 
> > Result: 1

对象

在操作对象时也有一些小技巧。

使用...运算符合并对象或数组中的对象

同样使用ES的...运算符可以替代人工操作,合并对象或者合并数组中的对象。

// 合并对象
const obj1 = {
    name: '大漠',
    url: 'w3cplus.com'
}

const obj2 = {
    name: 'airen',
    age: 30
}

const mergingObj = {...obj1, ...obj2}

> Result: {name: "airen", url: "w3cplus.com", age: 30}

// 合并数组中的对象
const array = [
    {
        name: '大漠',
        email: 'w3cplus@gmail.com'
    },
    {
        name: 'Airen',
        email: 'airen@gmail.com'
    }
]

const result = array.reduce((accumulator, item) => {
    return {
        ...accumulator,
        [item.name]: item.email
    }
}, {})

> Result: {大漠: "w3cplus@gmail.com", Airen: "airen@gmail.com"}

有条件的添加对象属性

不再需要根据一个条件创建两个不同的对象,以使它具有特定的属性。为此,使用...操作符是最简单的。

const getUser = (emailIncluded) => {
    return {
        name: '大漠',
        blog: 'w3cplus',
        ...emailIncluded && {email: 'w3cplus@hotmail.com'}
    }
}

const user = getUser(true)
console.log(user)
> Result: {name: "大漠", blog: "w3cplus", email: "w3cplus@hotmail.com"}

const userWithoutEmail = getUser(false)
console.log(userWithoutEmail)
> Result: {name: "大漠", blog: "w3cplus"}

解构原始数据

你可以在使用数据的时候,把所有数据都放在一个对象中。同时想在这个数据对象中获取自己想要的数据。在这里可以使用ES6的Destructuring特性来实现。比如你想把下面这个obj中的数据分成两个部分:

const obj = {
    name: '大漠',
    blog: 'w3cplus',
    email: 'w3cplus@hotmail.com',
    joined: '2019-06-19',
    followers: 45
}

let user = {}, userDetails = {}

({name: user.name, email: user.email, ...userDetails} = obj)
> {name: "大漠", blog: "w3cplus", email: "w3cplus@hotmail.com", joined: "2019-06-19", followers: 45}

console.log(user)
> Result: {name: "大漠", email: "w3cplus@hotmail.com"}

console.log(userDetails)
> Result: {blog: "w3cplus", joined: "2019-06-19", followers: 45}

动态更改对象的key

在过去,我们首先必须声明一个对象,然后在需要动态属性名的情况下分配一个属性。在以前,这是不可能以声明的方式实现的。不过在ES6中,我们可以实现:

const dynamicKey = 'email'

let obj = {
    name: '大漠',
    blog: 'w3cplus',
    [dynamicKey]: 'w3cplus@hotmail.com'
}

console.log(obj)
> Result: {name: "大漠", blog: "w3cplus", email: "w3cplus@hotmail.com"}

判断对象的数据类型

使用Object.prototype.toString配合闭包来实现对象数据类型的判断:

const isType = type => target => `[object ${type}]` === Object.prototype.toString.call(target)
const isArray = isType('Array')([1, 2, 3])

console.log(isArray)
> Result: true

上面的代码相当于:

function isType(type){
    return function (target) {
        return `[object ${type}]` === Object.prototype.toString.call(target)
    }
}

isType('Array')([1,2,3])
> Result: true

或者:

const isType = type => target => `[object ${type}]` === Object.prototype.toString.call(target)
const isString = isType('String')
const res = isString(('1'))

console.log(res)
> Result: true

检查某对象是否有某属性

当你需要检查某属性是否存在于一个对象,你可能会这样做:

var obj = {
    name: '大漠'
};

if (obj.name) { 
    console.log(true) // > Result: true
}

这是可以的,但是你需要知道有两种原生方法可以解决此类问题。in 操作符 和 Object.hasOwnProperty,任何继承自Object的对象都可以使用这两种方法。

var obj = {
    name: '大漠'
};

obj.hasOwnProperty('name');     // > true
'name' in obj;                  // > true

obj.hasOwnProperty('valueOf');  // > false, valueOf 继承自原型链
'valueOf' in obj;               // > true

两者检查属性的深度不同,换言之hasOwnProperty只在本身有此属性时返回true,而in操作符不区分属性来自于本身或继承自原型链。

这是另一个例子:

var myFunc = function() {
    this.name = '大漠';
};

myFunc.prototype.age = '10 days';
var user = new myFunc();

user.hasOwnProperty('name'); 
> Result: true

user.hasOwnProperty('age'); 
> Result: false, 因为age来自于原型链

创造一个纯对象

使用Object.create(null)可以创建一个纯对象,它不会从Object类继承任何方法(例如:构造函数、toString() 等):

const pureObject = Object.create(null);

console.log(pureObject);                //=> {}
console.log(pureObject.constructor);    //=> undefined
console.log(pureObject.toString);       //=> undefined
console.log(pureObject.hasOwnProperty); //=> undefined

数据类型转换

JavaScript中数据类型有NumberStringBooleanObjectArrayFunction等,在实际使用时会碰到数据类型的转换。在转换数据类型时也有一些小技巧。

转换为布尔值

布尔值除了truefalse之外,JavaScript还可以将所有其他值视为“真实的”或“虚假的”。除非另有定义,JavaScript中除了0''nullundefinedNaNfalse之外的值都是真实的

我们可以很容易地在真和假之间使用!运算符进行切换,它也会将类型转换为Boolean。比如:

const isTrue = !0;
const isFasle = !1;
const isFasle = !!0 // !0 => true,true的反即是false

console.log(isTrue)
> Result: true

console.log(typeof isTrue)
> Result: 'boolean'

这种类型的转换在条件语句中非常方便,比如将!1当作false

转换为字符串

我们可以使用运算符+后紧跟一组空的引号''快速地将数字或布尔值转为字符串:

const val = 1 + ''
const val2 = false + ''

console.log(val)
>  Result: "1"

console.log(typeof val)
> Result: "string"

console.log(val2)
> Result: "false"

console.log(typeof val2)
> Result: "string"

转换为数值

上面我们看到了,使用+紧跟一个空的字符串''就可以将数值转换为字符串。相反的,使用加法运算符+可以快速实现相反的效果。

let int = '12'
int = +int

console.log(int)
> Result: 12

console.log(typeof int)
> Result: 'number'

用同样的方法可以将布尔值转换为数值:

console.log(+true)
> Return: 1

console.log(+false)
> Return: 0

在某些上下文中,+会被解释为连接操作符,而不是加法运算符。当这种情况发生时,希望返回一个整数,而不是浮点数,那么可以使用两个波浪号~~。双波浪号~~被称为按位不运算符,它和-n - 1等价。例如, ~15 = -16。这是因为- (-n - 1) - 1 = n + 1 - 1 = n。换句话说,~ - 16 = 15

我们也可以使用~~将数字字符串转换成整数型:

const int = ~~'15'

console.log(int)
> Result: 15

console.log(typeof int)
> Result: 'number'

同样的,NOT操作符也可以用于布尔值: ~true = -2~false = -1

浮点数转换为整数

平常都会使用Math.floor()Math.ceil()Math.round()将浮点数转换为整数。在JavaScript中还有一种更快的方法,即使用|(位或运算符)将浮点数截断为整数。

console.log(23.9 | 0);  
> Result: 23

console.log(-23.9 | 0); 
> Result: -23

|的行为取决于处理的是正数还是负数,所以最好只在确定的情况下使用这个快捷方式。

如果n是正数,则n | 0有效地向下舍入。如果n是负数,它有效地四舍五入。更准确的说,该操作删除小数点后的内容,将浮点数截断为整数。还可以使用~~来获得相同的舍入效果,如上所述,实际上任何位操作符都会强制浮点数为整数。这些特殊操作之所以有效,是因为一旦强制为整数,值就保持不变。

|还可以用于从整数的末尾删除任意数量的数字。这意味着我们不需要像下面这样来转换类型:

let str = "1553"; 
Number(str.substring(0, str.length - 1));
> Result: 155

我们可以像下面这样使用|运算符来替代:

console.log(1553 / 10   | 0)  
> Result: 155

console.log(1553 / 100  | 0)  
> Result: 15

console.log(1553 / 1000 | 0)  
> Result: 1

使用!!操作符转换布尔值

有时候我们需要对一个变量查检其是否存在或者检查值是否有一个有效值,如果存在就返回true值。为了做这样的验证,我们可以使用!!操作符来实现是非常的方便与简单。对于变量可以使用!!variable做检测,只要变量的值为:0null" "undefined或者NaN都将返回的是false,反之返回的是true。比如下面的示例:

function Account(cash) {
    this.cash = cash;
    this.hasMoney = !!cash;
}

var account = new Account(100.50);
console.log(account.cash); 
> Result: 100.50

console.log(account.hasMoney); 
> Result: true

var emptyAccount = new Account(0);
console.log(emptyAccount.cash); 
> Result: 0

console.log(emptyAccount.hasMoney); 
> Result: false

在这个示例中,只要account.cash的值大于0,那么account.hasMoney返回的值就是true

还可以使用!!操作符将truthyfalsy值转换为布尔值:

!!""        // > false
!!0         // > false
!!null      // > false
!!undefined  // > false
!!NaN       // > false

!!"hello"   // > true
!!1         // > true
!!{}        // > true
!![]        // > true

小结

文章主要收集和整理了一些有关于JavaScript使用的小技巧。既然是技巧在必要的时候能帮助我们快速的解决一些问题。如果你有这方面的相关积累,欢迎在下面的评论中与我们一起分享。后续将会持续更新,希望对大家有所帮助。