0
点赞
收藏
分享

微信扫一扫

Html第4集:对象定义、typeof、instanceof、undefine


文章目录

  • ​​简单对象​​
  • ​​跨行定义对象​​
  • ​​typeof​​
  • ​​instanceof​​
  • ​​undefined​​
  • ​​undefined 和 null 的区别​​

简单对象

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试</title>

<script>

//定义对象
user = {name: "zhaoyanjun", age: 10, man: true}

//日志
console.log(user.name + user.age + user.man)

//对象赋值
user.name = "多多"
user.age = 3

//日志
console.log(user.name + user.age + user.man)

</script>

</head>
<body>

</body>
</html>

效果:

Html第4集:对象定义、typeof、instanceof、undefine_javascript

跨行定义对象

定义 JavaScript 对象可以跨越多行,空格跟换行不是必须的:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试</title>

<script>

//定义对象
user = {
name: "zhaoyanjun",
age: 10,
man: true
}

</script>

</head>
<body>

</body>
</html>

输出对象属性:

.log(user.name)
console.log(user["name"])

typeof

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试</title>

<script>

console.log(typeof 1)
console.log(typeof 2.3)
console.log(typeof "abc")
console.log(typeof false)
console.log(typeof [1, 2, 3])
console.log(typeof {name: "zyj"})

</script>

</head>
<body>

</body>
</html>

日志:

Html第4集:对象定义、typeof、instanceof、undefine_javascript_02

instanceof

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试</title>

<script>

a = new Number(1)

if (a instanceof Number) {
console.log("Number")
}

b = new String("abc")

if (b instanceof String) {
console.log("String")
}

c = new Boolean(false)

if (c instanceof Boolean) {
console.log("Boolean")
}

</script>

</head>
<body>

</body>
</html>

日志:

Html第4集:对象定义、typeof、instanceof、undefine_学习_03

undefined

在 JavaScript 中, undefined 是一个没有设置值的变量。

typeof 一个没有值的变量会返回 undefined。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试</title>

<script>
//没有定义
a

</script>

</head>
<body>

</body>
</html>

Html第4集:对象定义、typeof、instanceof、undefine_javascript_04

undefined 和 null 的区别

null 和 undefined 的值相等,但类型不等:

typeof undefined             // undefined
typeof null // object
null === undefined // false
null == undefined // true

1、比较

(1)undefined:是所有没有赋值变量的默认值,自动赋值。
(2)null:主动释放一个变量引用的对象,表示一个变量不再指向任何对象地址。

2、何时使用null?

当使用完一个比较大的对象时,需要对其进行释放内存时,设置为 null。

3、null 与 undefined 的异同点是什么呢?

  • 共同点:都是原始类型,保存在栈中变量本地。
  • 不同点:
    (1)undefined——表示变量声明过但并未赋过值。
    (2)null——表示一个变量将来可能指向一个对象。

它是所有未赋值变量默认值,例如:


举报

相关推荐

0 条评论