JavaScript 如何通过函数传递基本/对象类型
在本文中,我们将学习如何在JavaScript中通过函数传递基本/对象类型。首先,我们将了解JavaScript中的基本数据类型和对象数据类型:
1. 基本数据类型: JavaScript提供的预定义数据类型称为基本数据类型。JavaScript中的基本数据类型包括:
- 字符串: 字符串是JavaScript中用双引号(””)或单引号(”)括起来的字符集合。
- 数字: JavaScript有两种类型的数字,带有小数点和不带小数点的。
- 布尔: 只接受true和false。
- 空: 表示空值或未定义的值。
- 未定义: 当变量的值没有被赋值时,变量的值将为未定义。
2. 对象数据类型: 它属于非基本数据类型。在JavaScript中,基于基本数据类型导出的数据类型称为非基本数据类型。对象和数组都属于非基本数据类型,但在这里我们只看对象数据类型。
示例: 下面的示例显示了JavaScript中的所有上述数据类型。
Javascript
<script>
// Primitive Datatype
// String
let s = "Hello"
let p = 'Hii';
console.log(s);
console.log(p);
// Number
let q = 10.65;
let r = 20;
console.log(q);
console.log(r);
// Boolean
console.log(10>9);
console.log(9>10);
// Null
let z = null;
console.log(z);
// Undefined
let x;
console.log(x);
// Object Datatype
// Car is a object
let car = {
name: 'TATA',
color : 'red',
}
// Calling the object data and print them
console.log(car.name);
console.log(car.color);
</script>
输出:
Hello
Hii
10.65
20
true
false
null
undefined
TATA
red
现在让我们来看看在JavaScript中如何通过函数传递原始/对象数据类型。首先,我们将看看如何在函数中传递原始类型,然后再看对象。
在函数中传递原始类型: 原始类型始终按值传递。这些是不可变的。这意味着即使我们在函数中改变了值,原始值也不会改变。JavaScript中共有五种原始数据类型。以下示例将演示此方法。
示例1(字符串): 我们通过函数print传递了两个字符串值或参数。
Javascript
<script>
function print(y, z) {
return y + " " + z;
}
// Here the function print is called and
// the argument is passed and store the
// value in x
let x = print("Hello", "everyone");
console.log(x);
</script>
输出:
Hello everyone
示例2(数字): 我们通过函数print传递数字(有小数和无小数)。 ****
Javascript
<script>
function print(y, z) {
console.log(y);
console.log(z);
console.log(y + z);
}
// Here the function print is called
// and the argument is passed
print(10, 20.5);
</script>
输出:
10
20.5
30.5
示例3(布尔型): 我们通过函数print将数字传递进去,如果条件满足则返回“true”,否则返回“false”。
Javascript
<script>
function print(y, z) {
return y > z;
}
// Call the function print and passing
// arguments and the function return
// true or false
console.log(print(50, 40));
</script>
输出:
true
示例 4(空值):
我们将null变量传递给函数print,结果打印出了null本身。
Javascript
<script>
function print(y) {
console.log(y);
}
let x = null;
print(x);
</script>
输出:
null
示例5(未定义): 在这里,我们通过print函数传递了未定义的变量。
JavaScript
<script>
function print(y) {
console.log(y);
}
// Here value is not assigned
let x;
print(x);
</script>
输出:
undefined
在函数中传递对象类型:
对象通过引用传递。如果函数中的对象属性被改变,原始值也会改变。
示例:
在下面的示例中,我们创建了一个名为laptop的对象,并将其传递给print函数。
Javascript
<script>
// Create a laptop object
let laptop = {
name: "Dell",
color: "black",
quantity: 1
};
// Call the function print where
// we pass the laptop object
print(laptop);
// Print the object
function print(obj) {
console.log(obj.name);
console.log(obj.color);
console.log(obj.quantity);
}
</script>
输出:
Dell
black
1