js 变量类型

版权声明:本文为博主原创文章,如需转载请务必注明原地址。 https://blog.csdn.net/qq_31393401/article/details/82658831

知识点

  • 变量类型
  • 变量计算
  • 传递参数

变量类型

  • 基本类型 VS 引用类型
  • typeof运算符详解

基本类型

Number/String/Boolean/undefined/null
基本类型的值在内存中占据固定大小的空间,因此被保存在堆内存中。

var a = 100
var b = a
a = 200
console.log(b) // 200

引用类型

Object/Array/Function
引用类型是保存在内存中的对象,其指针指向同一个内存,原因是其可以无限制扩展属性,为了防止消耗过大内存。操作对象时实际是在操作对象的引用而不是实际的对象。

var a = {age:200}
var b = a
b = {age:100}
console.log(a.age) // 100

变量计算-强制类型转换

  • 字符串拼接
  • ==运算符
  • if语句
  • 逻辑运算
var a = 100 + 10 // 110
var b = 100 + '10' // '10010'
// == 会将数据转换某一基本类型
100 == '100' // true
0 == '' // true
null == undefined // true
// if会将数据转换为Boolean
var a = true, b = 100, c = ''
if (a) {} // true
if (b) {} // true
if (c) {} // false
console.log(10 && 0) // 0,10被转为了true
console.log('' || 'abc') // 'abc',''被转为了false
console.log(!window.abc) // true,undefined被转为了false

// 判断一个变量会被当成true还是false
var a = 100
console.log(!!a)

传递参数

ECMAScript中所有函数的参数都是按值传递的,就如同复制变量。
但向函数传递引用类型的值时,会将其在内存中的地址复制给函数中的局部变量,因此这个局部变量的变化会反映在函数的外部,而基本类型传参则不会反映到函数外部。

// 基本类型传参
function addTen(num){
	num += 10
	return num
}
var count = 20
var result = addTen(count)
alert(count) // 20,没有变化
alert(result) // 30

// 引用类型传参
fucntion setName(obj){
	obj.name = 'David'
}
var person = new Object()
setName(person)
alert(person.name) // 'David'

猜你喜欢

转载自blog.csdn.net/qq_31393401/article/details/82658831