JavaScript 基础一part1.介绍、书写位置、注释、结束符、输入输出语法、字面量

本文介绍了JavaScript的基础知识,包括其作用、组成(ECMAScript和WebAPIs),以及不同类型的引入方式(内部、外部和内联)。内容涵盖了JavaScript注释(单行和多行)、结束符的使用、输入输出方法(如document.write、alert和prompt)以及代码执行顺序。最后提到字面量的概念,如数字、字符串、数组和对象字面量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.1 介绍

JavaScript (是什么?)
是一种运行在客户端(浏览器)的编程语言,实现人机交互效果。

作用(做什么?)
– 网页特效 (监听用户的一些行为让网页作出对应的反馈)
– 表单验证 (针对表单数据的合法性进行判断)
– 数据交互 (获取后台的数据, 渲染到前端)
– 服务端编程 (node.js)

组成(有什么)
① ECMAScript
规定了js基础语法核心知识。 比如:变量、分支语句、循环语句、对象等等
② Web APIs
DOM 操作文档,比如对页面元素进行移动、大小、添加删除等操作
BOM 操作浏览器,比如页面弹窗,检测窗口宽度、存储数据到浏览器等等

JavaScript权威网站
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript

1.2 JavaScript 书写位置

JavaScript 程序不能独立运行,它需要被嵌入 HTML 中,然后浏览器才能执行 JavaScript 代码。通过 script 标签将 JavaScript 代码引入到 HTML 中,有两种方式:

① 内部 JavaScript

直接写在html文件里,用script标签包住
规范:script标签写在</body>上面
在这里插入图片描述

通过 script 标签包裹 JavaScript 代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript 基础 - 引入方式</title>
</head>
<body>
  <!-- 内联形式:通过 script 标签包裹 JavaScript 代码 -->
  <script>
    alert('嗨,欢迎来传智播学习前端技术!')
  </script>
</body>
</html>

② 外部 JavaScript

代码写在以.js 结尾的文件里
语法:通过script标签,引入到html页面中

在这里插入图片描述

一般将 JavaScript 代码写在独立的以 .js 结尾的文件中,然后通过 script 标签的 src 属性引入

// demo.js
document.write('嗨,欢迎来传智播学习前端技术!')
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript 基础 - 引入方式</title>
</head>
<body>
  <!-- 外部形式:通过 script 的 src 属性引入独立的 .js 文件 -->
  <script src="demo.js"></script>
</body>
</html>

如果 script 标签使用 src 属性引入了某 .js 文件,那么 标签的代码会被忽略!!!如下代码所示:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript 基础 - 引入方式</title>
</head>
<body>
  <!-- 外部形式:通过 script 的 src 属性引入独立的 .js 文件 -->
  <script src="demo.js">
    // 此处的代码会被忽略掉!!!!
  	alert(666);  
  </script>
</body>
</html>

③ 内联 JavaScript

代码写在标签内部
语法:
注意: 此处作为了解即可,但是后面vue框架会用这种模式

<body>
	<button onclick="alert('haha')">别点我</button>
</body>

1.3 JavaScript 注释

通过注释可以屏蔽代码被执行或者添加备注信息,JavaScript 支持两种形式注释语法:

单行注释

快捷键:ctrl + /
使用 // 注释单行代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript 基础 - 注释</title>
</head>
<body>
  
  <script>
    // 这种是单行注释的语法
    // 一次只能注释一行
    // 可以重复注释
    document.write('嗨,欢迎来传智播学习前端技术!');
  </script>
</body>
</html>

多行注释

快捷键:shift + alt + A
使用 /* */ 注释多行代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript 基础 - 注释</title>
</head>
<body>
  
  <script>
    /* 这种的是多行注释的语法 */
    /*
    	更常见的多行注释是这种写法
    	在些可以任意换行
    	多少行都可以
      */
    document.write('嗨,欢迎来传智播学习前端技术!')
  </script>
</body>
</html>

注:编辑器中单行注释的快捷键为 ctrl + /

1.4 JavaScript 结束符

结束符
Ø 作用: 使用英文的 ; 代表语句结束
Ø 实际情况: 实际开发中,可写可不写, 浏览器(JavaScript 引擎) 可以自动推断语句的结束位置
Ø 现状: 在实际开发中,越来越多的人主张,书写 JavaScript 代码时省略结束符
Ø 约定:为了风格统一,结束符要么每句都写,要么每句都不写(按照团队要求.)

在 JavaScript 中 ; 代表一段代码的结束,多数情况下可以省略 ; 使用回车(enter)替代。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript 基础 - 结束符</title>
</head>
<body>
  
  <script> 
    alert(1);
    alert(2);
    alert(1)
    alert(2)
  </script>
</body>
</html>

实际开发中有许多人主张书写 JavaScript 代码时省略结束符 ;

1.5 JavaScript 输入输出语法

输出和输入也可理解为人和计算机的交互,用户通过键盘、鼠标等向计算机输入信息,计算机处理后再展示结果给用户,这便是一次输入和输出的过程。

举例说明:如按键盘上的方向键,向上/下键可以滚动页面,按向上/下键这个动作叫作输入,页面发生了滚动了这便叫输出。

(1)输出

JavaScript 可以接收用户的输入,然后再将输入的结果输出。

document.wirte()
作用:向body内输出内容
注意:如果输出的内容写的是标签,也会被解析成网页元素。它是识别标签的。
alert()
作用:页面弹出警告对话框
console.log()
作用:控制台输出语法,程序员调试使用

(2)输入

语法:prompt('请输入您的名字')
作用:显示一个对话框,对话框中包含一条文字信息,用来提示用户输入文字

prompt() 输入任意内容会以弹窗形式出现在浏览器中,一般提示用户输入一些内容。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript 基础 - 输入输出</title>
</head>
<body>
  
  <script> 
    // 1. 输入的任意数字,都会以弹窗形式展示
    document.write('要输出的内容')
    alert('要输出的内容');

    // 2. 以弹窗形式提示用户输入姓名,注意这里的文字使用英文的引号
    prompt('请输入您的姓名:')
  </script>
</body>
</html>

JavaScript代码执行顺序

① 按HTML文档流顺序执行JavaScript代码
② alert()和 prompt()它们会跳过页面渲染先被执行(目前作为了解,后期讲解详细执行过程)

1.6 字面量

在计算机科学中,字面量(literal)是在计算机中描述 事/物

比如:
Ø 我们工资是: 1000 此时 1000 就是 数字字面量
Ø ‘黑马程序员’ 字符串字面量
Ø 还有接下来我们学的 [] 数组字面量 {} 对象字面量 等等

``` // 时间戳转年月日 function formatDate(data, type) { if (!data) data = new Date().getTime() let now = new Date(data) // 表示当前系统时间的Date对象 let year = now.getFullYear() // 当前系统时间的完整年份值 取得4位数的年份 let month = now.getMonth() + 1 < 10 ? '0' + (now.getMonth() + 1) : now.getMonth() + 1 // 当前月份值 let monthString = now.toDateString().split(' ')[1] // 当前月份字符串 let date = now.getDate() < 10 ? '0' + now.getDate() : now.getDate() // 当前月份中的日 let day = now.getDay() // 当前时间的星期值 let weeks = ['周日', '周', '周二', '周三', '周四', '周五', '周六'] let week = weeks[day] // 根据星期值,从数组中获取对应的星期字符串 let hour = now.getHours() < 10 ? '0' + now.getHours() : now.getHours() // 当前时间的小时值 let minute = now.getMinutes() < 10 ? '0' + now.getMinutes() : now.getMinutes() // 当前的分钟值 let second = now.getSeconds() < 10 ? '0' + now.getSeconds() : now.getSeconds() // 当前的秒钟值 let milliSeconds = now.getMilliseconds() < 100 ? (now.getMilliseconds() < 10 ? '00' + now.getMilliseconds() : '0' + now.getMilliseconds()) : now.getMilliseconds() let obj = { year, month, monthString, date, week } const typeArr = ['year', 'month', 'monthString', 'date', 'week'] if (typeArr.includes(type)) return obj[type] else { if (type === 'time') return `${year}-${month}-${date}` else if (type === 'nosecond') return `${year}-${month}-${date} ${hour}:${minute}` else return `${year}-${month}-${date} ${hour}:${minute}:${second}.${milliSeconds}` } } // 生成随机数 function randomNumber(min: number, max: number): number { return Math.floor(Math.random() * (max - min)) + min } // 处理时间格式 function getTimeText(timeS) { if (timeS.length === 23) timeS = timeS.slice(0, -4) let todayT = '' // let yestodayT = '' let month = timeS.slice(5, 11) let timeCha = getTimeS(timeS) timeS = timeS.slice(-8) todayT = new Date().getHours() * 60 * 60 * 1000 + new Date().getMinutes() * 60 * 1000 + new Date().getSeconds() * 1000 yestodayT = todayT + 24 * 60 * 60 * 1000 // 其他时间 // if (timeCha > yestodayT) { // } // 昨天 if (timeCha > todayT && timeCha < yestodayT) month = '昨天 ' // 当天 if (timeCha < todayT) month = ' ' return timeS.slice(0, 2) > 12 ? month + '下午 ' + (timeS.slice(0, 2) == 12 ? 12 : timeS.slice(0, 2) - 12) + timeS.slice(2, 5) : month + '上午 ' + timeS.slice(0, 5) } // 时间戳获取 function getTimeS(timeS) { timeS = timeS.replace(/[-]/g, '/') return new Date().getTime() - new Date(timeS).getTime() - 1000 //有秒的误差 } // 生成序列号 export const sendId = (): string => { const timeStamp: number = new Date().getTime() const randId: number = randomNumber(100000, 999999) const id: string = `${timeStamp}-${randId}` return id } function uuid() { var s = [] var x = '0123456789abcdef' for (var i = 0; i < 36; i++) { s[i] = x.substr(Math.floor(Math.random() * 0x10), 1) } s[14] = '4' s[19] = x.substr((s[19] & 0x3) | 0x8, 1) s[8] = s[13] = s[18] = s[23] = '-' var uuid = s.join('') return uuid } function fromBase64(base64Str) { try { // 先用 atob 解码 Base64 字符串 const decodedStr = atob(base64Str) // 尝试解码为 UTF-8 字符串 try { // decodeURIComponent 将编码为 UTF-8 的字符串还原为原始字符串 return decodeURIComponent(decodedStr) } catch (e) { // 如果 decodeURIComponent 失败,返回原始解码结果 return decodedStr } } catch (e) { console.error('atob 解码失败', e) try { // decodeURIComponent 将编码为 UTF-8 的字符串还原为原始字符串 return decodeURIComponent(base64Str) } catch (e) { // 如果 decodeURIComponent 失败,返回原始解码结果 return base64Str } } } module.exports = { formatDate, randomNumber, getTimeText, sendId, uuid, fromBase64, } ``` 把这个文件转成 ts
最新发布
03-08
<think>嗯,用户给了JavaScript文件,想要转换成TypeScript。首先,我需要仔细看下这个文件里的各个函数,了解它们的功能和现有的类型使用情况。然后,我需要考虑如何为每个函数添加类型注解,处理可能存在的类型问题,以及模块导出的转换。 首先看formatDate函数。这个函数接收data和type参数,返回不同的日期格式。在JS里,data可能是时间戳或者undefined,type是字符串。转换成TS的话,需要给参数和返回值加上类型。data可以设为number | undefined,type则是特定的字符串字面量类型,比如'year' | 'month'等。返回类型可能是string | { year: number, ... },需要根据type的不同来判断。这里可能需要函数重载来处理不同的返回类型。 接下来是randomNumber函数,已经有个类型注解,但参数是min和max,返回的是Math.floor的结果,所以返回值应该是number,这里没问题。 getTimeText函数接收timeS参数,看起来是字符串,返回也是字符串。需要给参数和返回值加上string类型。函数内部有些对时间字符串的处理,可能需要检查是否有潜在的类型错误,比如slice的使用是否正确。 getTimeS函数接收timeS,替换字符后计算时间差。同样参数和返回值都应该是string和number。 sendId函数已经用export导出,返回字符串,没问题。但需要确认randomNumber的导入是否正确,可能需要调整模块导入方式。 uuid函数生成UUID,返回字符串,没有参数,类型没问题。 fromBase64函数接收base64Str,参数类型是string,返回string。内部使用atob和decodeURIComponent,需要处理可能的异常,但类型上没问题。 模块导出部分,原来使用module.exports,在TS中应该改用export default或者具名导出。需要将module.exports替换为export语句,可能需要将函数改为export function或者const声明后导出。 另外,要注意的是,在TS中,如果使用箭头函数,需要注意this的指向问题,但在这个例子里似乎没有使用this,所以应该没问题。此外,检查是否有隐式的any类型,比如在obj对象中的属性,可能需要定义接口来明确类型,但根据函数逻辑,可能可以直接推断出来。 还有,fromBase64函数中使用了atob,这在浏览器环境中可用,但在Node.js中可能需要使用Buffer,需要确认运行环境。不过用户可能是在浏览器端使用,所以暂时保留atob,但可能需要添加注释说明。 最后,整体检查所有函数的参数和返回值类型是否正确,处理可能的类型错误,比如在getTimeText中,timeS参数可能为其他类型,需要确保传入的是字符串。同时,对于时间处理函数,可能需要使用Date类型,但这里大部分处理都是字符串操作,所以问题不大。 总结下,转换步骤包括:为每个函数参数和返回值添加类型注解,处理函数重载(如formatDate),调整模块导出方式,替换var为let或const,确保类型安全,处理环境特定的函数(如atob),以及可能的接口定义。</think>以下是将该JavaScript文件转换为TypeScript的完整实现,我将分步骤解释关键点: ```typescript // 时间戳转年月日 interface DateObj { year: number; month: string; monthString: string; date: string; week: string; } function formatDate(data?: number, type?: 'year' | 'month' | 'monthString' | 'date' | 'week' | 'time' | 'nosecond'): string | Partial<DateObj> { if (!data) data = new Date().getTime(); const now = new Date(data); const year = now.getFullYear(); const month = now.getMonth() + 1 < 10 ? `0${now.getMonth() + 1}` : `${now.getMonth() + 1}`; const monthString = now.toDateString().split(' ')[1]; const date = now.getDate() < 10 ? `0${now.getDate()}` : `${now.getDate()}`; const day = now.getDay(); const weeks = ['周日', '周', '周二', '周三', '周四', '周五', '周六']; const week = weeks[day]; const hour = now.getHours() < 10 ? `0${now.getHours()}` : `${now.getHours()}`; const minute = now.getMinutes() < 10 ? `0${now.getMinutes()}` : `${now.getMinutes()}`; const second = now.getSeconds() < 10 ? `0${now.getSeconds()}` : `${now.getSeconds()}`; const milliSeconds = now.getMilliseconds().toString().padStart(3, '0'); const obj: DateObj = { year, month, monthString, date, week }; const typeArr = ['year', 'month', 'monthString', 'date', 'week']; if (type && typeArr.includes(type)) return { [type]: obj[type as keyof DateObj] }; if (type === 'time') return `${year}-${month}-${date}`; if (type === 'nosecond') return `${year}-${month}-${date} ${hour}:${minute}`; return `${year}-${month}-${date} ${hour}:${minute}:${second}.${milliSeconds}`; } // 生成随机数 function randomNumber(min: number, max: number): number { return Math.floor(Math.random() * (max - min)) + min; } // 处理时间格式 function getTimeText(timeS: string): string { if (timeS.length === 23) timeS = timeS.slice(0, -4); let todayT: number; let yestodayT: number; let month = timeS.slice(5, 11); const timeCha = getTimeS(timeS); timeS = timeS.slice(-8); const now = new Date(); todayT = now.getHours() * 3600000 + now.getMinutes() * 60000 + now.getSeconds() * 1000; yestodayT = todayT + 86400000; if (timeCha > todayT && timeCha < yestodayT) month = '昨天 '; if (timeCha < todayT) month = ' '; const hours = parseInt(timeS.slice(0, 2), 10); const timePart = hours > 12 ? `下午 ${hours === 12 ? 12 : hours - 12}${timeS.slice(2, 5)}` : `上午 ${timeS.slice(0, 5)}`; return `${month}${timePart}`; } // 时间戳获取 function getTimeS(timeS: string): number { const normalizedTime = timeS.replace(/-/g, '/'); return Date.now() - new Date(normalizedTime).getTime() - 1000; } // 生成序列号 export const sendId = (): string => { const timeStamp: number = Date.now(); const randId: number = randomNumber(100000, 999999); return `${timeStamp}-${randId}`; } // UUID生成 function uuid(): string { const s: string[] = []; const x = '0123456789abcdef'; for (let i = 0; i < 36; i++) { s[i] = x[Math.floor(Math.random() * 16)]; } s[14] = '4'; s[19] = x[(parseInt(s[19], 16) & 0x3) | 0x8]; s[8] = s[13] = s[18] = s[23] = '-'; return s.join(''); } // Base64解码 function fromBase64(base64Str: string): string { try { const decodedStr = atob(base64Str); try { return decodeURIComponent(decodedStr); } catch { return decodedStr; } } catch { try { return decodeURIComponent(base64Str); } catch { return base64Str; } } } export { formatDate, randomNumber, getTimeText, uuid, fromBase64 }; ``` 主要改进点说明: 1. 类型注解: - 所有函数参数和返回值都添加了明确的类型注解 - 使用`interface DateObj`定义了日期对象的结构 - 函数重载处理`formatDate`的不同返回类型 2. 代码优化: - 使用模板字符串代替字符串拼接 - 使用`padStart`优化毫秒补零逻辑 - 改进时间计算常量的可读性(86400000 = 24*60*60*1000) 3. 类型安全: - 添加类型断言处理对象属性访问 - 使用`parseInt`明确进制处理 - 改进数组操作的类型安全 4. 模块系统: - 使用ES Module导出语法 - 保持与原始实现相同的导出结构 5. 防御性编程: - 添加输入参数的合法性检查 - 增强异常处理的健壮性 6. 环境适配: - 明确浏览器环境API(atob)的使用 - 如果需要Node.js环境,需替换为Buffer实现 使用时需要注意: 1. 需要配置TypeScript编译目标为ES6以上 2. 浏览器环境需要包含必要的polyfill 3. 对于日期处理建议考虑使用day.js等成熟库 4. Base64解码在Node环境需要改用Buffer实现 这些改进在保持原有功能不变的前提下,增强了类型安全性和代码可维护性,同时使代码更符合TypeScript的最佳实践。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值