JS实用篇复习笔记(3)

173 阅读2分钟

1、运算

1、数学运算是安全的 我们可以做任何事情:除以零,将非数字字符串视为数字等。

脚本永远不会因致命错误而停止。在最坏的情况下,我们会得到NaN结果

2、基本四则运算支持

3、说一下 取余数 和 求幂运算

alert( 5 % 2 ); // 1, a remainder of 5 divided by 2 
alert( 8 % 3 ); // 2, a remainder of 8 divided by 3
alert( 2 ** 2 ); // 2² = 4 
alert( 2 ** 3 );// 2³ = 8 
alert( 2 ** 4 ); // 2⁴ = 16

4、递增 ++ 和递减 --

let counter = 2; counter++; // works the same as counter = counter + 1, but is shorter alert( counter ); // 3
counter--; // works the same as counter = counter - 1, but is shorter 
alert( counter ); // 1
  • 注意 递增/递减只能应用于变量。尝试在类似的值上使用它5++会出错
  • 然后 放的位置 会造成一点差异 记住 ++ a 表示先加 再运算 对应的就很明确

image.png

5、还有使用比较多的是 ?

xxx && xxx

||

axxxb ? c : d

6、注意这六个

image.png

2、数据类型

  • 基本类型 string,number,bigint,boolean,null,undefined(未定义的值),symbol

  • 复杂类型 object(array,function)

  • type 判断 基本类型

typeof undefined // "undefined"
typeof 0 // "number" 
typeof 10n // "bigint" 
typeof true // "boolean" 
typeof "foo" // "string" 
typeof Symbol("id") // "symbol" 
typeof Math // "object" (1)
typeof null // "object" (2)
typeof alert // "function" (3)
  • instanceof 判断复杂类型 instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上

3、浏览器交互3种方法

  • alert
alert('you are cool!')

显示一条消息。
  • prompt

    显示一条消息,要求用户输入文本。它返回文本,或者,如果取消按钮或被Esc单击,则返回null

let age = prompt('How old are you?', 18);
alert(`You are ${age} years old!`); // You are 18 years old!
  • confirm

    显示一条消息并等待用户按“确定”或“取消”。它返回trueOK 和falseCancel/ Esc

它们暂停脚本执行并且不允许访问者与页面的其余部分进行交互,直到窗口被关闭

let isBoss = confirm("Are you the boss?");
alert( isBoss ); // true if OK is pressed

  • 会阻塞页面其他部分执行

4、需要注意的类型转化

1、转为Number类型

alert( Number(" 123 ") );// 123
alert( Number("123z") ); // NaN (error reading a number at "z") 
alert( Number(true) ); // 1 
alert( Number(false) ); // 0

image.png 2、转为字符串

'ok' + 1 // 'ok1'
String(value)

3、转为 布尔值

alert( Boolean(1) ); // true 
alert( Boolean(0) ); // false 
alert( Boolean("hello") ); // true 
alert( Boolean("") ); // false
  • 注意 Boolean(' ') // 里面放个空格 结果为 true Boolean('0') // 结果也为 true

image.png