Henry
发布于 2024-10-29 / 15 阅读
0
0

Node.js - 前置学习(一) - JavaScript 词汇语法

简介

使用 Node.js 的前置学习系列笔记之一

前置条件

样例需求

  • NA

学习笔记

参考链接

注释

单行注释 // line comment 和 块注释 /* block comment */,在注释中的代码和文字不会被读取执行。

样例代码 0000_js_comment.js

// this is the first line comment
// console.log('Line comment to ignore this code!');

console.log('Hello World!');

/*
    Multi-line comment
    console.log('Block comment, not execute this code!');
*/

执行结果

(base) myserver@myserver:/pega/nodejs/get_start/pre_0001_js_grammar$ node 0000_js_comment.js 
Hello World!

标识符

// 变量
const a = 1;
var b = 2;

// 方法
function fn(msg) {
	console.log(msg);
}

// 对象
const obj = {
	key: 'value'
};

// 类
class SampleClass {
	#private_property = 'private value' // 私有变量
	public_property = 'public value'
}

lbl: console.log('label'); // 标签

模板文字(模板字符串)

模板文字是用反引号 (```) 字符分隔的文字,允许使用嵌入表达式的 多行字符串、字符串插值 以及称为 标记模板 的特殊构造。

样例代码 0002_js_template_literals.js

// 模板字符串中使用转义字符

console.log(`\`` === "`"); //true

// 多行字符串

const multi_line = `Line 1 
Line 2
    Line 3` // 第三行前面有4个空格

console.log(multi_line);

// 字符串插值

const val_1 = 5;
const val_2 = 10;
console.log("Fifteen is " + (val_1 + val_2) + " and\nnot " + (2 * val_1 + val_2) + ".");
console.log(`Fifteen is ${val_1 + val_2} and
not ${2 * val_1 + val_2}.`);

// 标记模板

const person = "Apple"
const age = "28"

function myTagFn(myString, personExpresion, ageExpression) {
    const str0 = myString[0]; // 第一个 expression 以前的字符串
    const str1 = myString[1]; // 第一个 expression 至第二个 expression 中间的字符串
    const str2 = myString[2]; // 第二个 expression 之后的字符串

    const mapToAgeStr = ageExpression < 100 ? "youngster" : "centenarian";

    // 拼接转化后字符串
    return `${str0}${personExpresion}${str1}${mapToAgeStr}${str2}`;
}

const outputStr = myTagFn`That ${person} is a ${age}.`;

console.log(outputStr);

运行结果

(base) myserver@myserver:/pega/nodejs/get_start/pre_0001_js_grammar$ node 0002_js_template_literals.js 
true
Line 1 
Line 2
    Line 3
Fifteen is 15 and
not 20.
Fifteen is 15 and
not 20.
That Apple is a youngster.

通用模板生成器样例代码 0003_js_common_template.js

 // define common template

function common_template (myStrings, ...keys) {
    return (...values) => {
        // Get object to dict
        const dict = values[values.length - 1] || {};

        // add first string to result
        const result = [myStrings[0]];

        // use forEach to get value
        keys.forEach((key, i) => {
            const value = Number.isInteger(key) ? values[key] : dict[key];
            result.push(value, myStrings[i+1]);
        });

        // join result with "" and return
        return result.join("");
    }
}

// example 1 without object
const my_temp_1 = common_template`${0}${1}${0}!`;
const my_temp_2 = common_template(["","","","!"],0,1,0);
console.log(`my_temp_1: ${my_temp_1('Y',"A")}`);
console.log(`my_temp_2: ${my_temp_2('Y',"A")}`);

// example 2 with object
const my_temp_3 = common_template`${0} ${"foo"}!`;
const my_temp_4 = common_template([""," ","!"],0,"foo");
console.log(`my_temp_3: ${my_temp_3("hello",{foo: "world"})}`);
console.log(`my_temp_4: ${my_temp_4("hello",{foo: "world"})}`);

// example 3 with complex string and object
const my_temp_5 = common_template`I'm ${"name"}, I'm almost ${"age"} years old. I like play ${0}.`;
const my_temp_6 = common_template(["I'm ",", I'm almost "," years old. I like play ","."],"name","age",0);
console.log(`my_temp_5: ${my_temp_5("basketball",{name: "Apple",age: 28})}`);
console.log(`my_temp_6: ${my_temp_6("basketball",{name: "Apple",age: 28})}`);

运行结果

(base) myserver@myserver:/pega/nodejs/get_start/pre_0001_js_grammar$ node 0003_js_common_template.js 
my_temp_1: YAY!
my_temp_2: YAY!
my_temp_3: hello world!
my_temp_4: hello world!
my_temp_5: I'm Apple, I'm almost 28 years old. I like play basketball.
my_temp_6: I'm Apple, I'm almost 28 years old. I like play basketball.

更多内容请查看文中参考链接,谢谢!


评论