JavaScript 如何检查值是否为原始值
JavaScript提供了六种原始值类型,包括数字、字符串、布尔值、未定义值、符号和大整数。原始值的大小是固定的,因此JavaScript将原始值存储在调用堆栈 ****(执行上下文)中。
当我们访问原始值时,我们操作的是存储在变量中的实际值。因此,原始类型的变量通过值 访问 。当我们将存储原始值的变量分配给另一个变量时,变量中存储的值会被创建并复制到新变量中。
为了检查一个值是不是原始值,我们可以使用以下方法:
方法1
在这种方法中,我们使用 typeof运算符 检查值的类型。如果值的类型是“object”或“function”,则该值不是原始值,否则它是原始值。但是,typeof运算符会将null显示为“object”,但实际上null是一个原始值。
示例:
let isPrimitive = (val) => {
if(val === null){
console.log(true);
return;
}
if(typeof val == "object" || typeof val == "function"){
console.log(false)
}else{
console.log(true)
}
}
isPrimitive(null)
isPrimitive(12)
isPrimitive(Number(12))
isPrimitive("Hello world")
isPrimitive(new String("Hello world"))
isPrimitive(true)
isPrimitive([])
isPrimitive({})
输出:
true
true
true
true
false
true
false
false
方法2
在这个方法中,我们将值传递给 Object() ,然后检查该值是否等于 Object(value) 。如果值相等,则该值是原始值,否则不是原始值。
示例:
let isPrimitive = (val) => {
if(val === Object(val)){
console.log(false)
}else{
console.log(true)
}
}
isPrimitive(null)
isPrimitive(12)
isPrimitive(Number(12))
isPrimitive("Hello world")
isPrimitive(new String("Hello world"))
isPrimitive(true)
isPrimitive([])
isPrimitive({})
输出结果:
true
true
true
true
false
true
false
false
极客教程