JavaScript快速入门(4):表达式

本系列随笔是本人的学习笔记,初学阶段难免会有理解不当之处,错误之处恳请指正。另:转载请注明出处。

基本表达式

JavaScript 支持的操作符列表:

+ - * / % ++ --
= += -= *= /= %=
== === != !== > < >= <= ?
&& || !
& | ~ ^ << >> <<<
typeof instanceof

其详细介绍请参考:W3Schools: JavaScript Operators

== 与 === 的区别

其中:

  • == 操作符用于比较两个值(可以是表达式)是否相等
  • === 操作符比 == 更加严格,它还会检测两个值的类型是否相同

示例:

var n = 123;
var s = "123";
alert(n == s);      // true
alert(n === s);     // false
alert(n === 123);   // true
alert(s === "123"); // true
alert(null == undefined);  // true
alert(null === undefined); // false

正则表达式

JavaScript 采用 Perl 中正则表达式的语法,格式:

/pattern/modifiers

示例:

var s = "https://www.baidu.com/";
if (/www\.\S+\.com/i.test(s)) { // 判断字符串与正则式是否匹配
    console.log("String " + s + " matches the pattern");
    var pattern = /(https?):\/\/www\.([^\/]+)/i;
    var groups = pattern.exec(s);      // 获取分组,返回一个数组,第0个元素为完全匹配的内容,其余依次为各个分组的内容
    console.log('URL: ' + groups[0]);      // https://www.baidu.com 注意这里没有右斜线
    console.log('Protocol: ' + groups[1]); // https
    console.log('Domain: '   + groups[2]); // baidu.com
}

完。

猜你喜欢

转载自www.cnblogs.com/itwhite/p/12218024.html