Home > Web Front-end > JS Tutorial > body text

A journey of data types in Javascript_Basic knowledge

WBOY
Release: 2016-05-16 15:36:10
Original
1274 people have browsed it

Although Javascript is a weakly typed language, it also has several data types of its own, namely: Number, String, Boolean, Object, Udefined, and Null. Among them, Object is a complex data type, and Object consists of unordered key-value pairs. The remaining several types are simple data types. Note: The first letter of the variable type is capitalized, while the first letter of the variable value is lowercase.

JavaScript does not support custom types, so all values ​​in JavaScript belong to one of these six types.
According to the ECMAScript 5.1 specification, there are six data types in JavaScript, namely: Undefined, Null, Boolean, Number, String, and Object. The first five are basic types, and the last one is Object type.

The latest ECMAScript 6 adds another type: Symbol (ECMAScript 6 new definition)

Basic data types

Undefined: There is only one value, undefined, which means "no value" and applies to all data types.
Null: There is only one value, null, which means "no object" and only applies to object types. (literal)
Boolean: There are two values, true and false
Number: The value is a collection of 64-bit floating point numbers following the IEEE 754 standard, and there is no integer data structure. In addition, it also contains three special values: NaN, Infinity, -Infinity
String: The value is a collection of finite Unicode characters. Must be enclosed in ' or ".

1. String

JavaScript’s string type is used to represent text data. It is an "element" of a set of 16-bit unsigned integer values. Each element in the string occupies a position in the string. The first element has index 0, the next has index 1, and so on. The length of a string is the number of its elements

Unlike the C language, strings in JavaScript are immutable (Annotation: For example, string operations in JavaScript must return a new string, and the original string has not been changed)

Everything in Javascript is object-based

Create string, there are two types

1. The string created using literal method is the basic type of string //string

2. The string created using String() is a basic type of string // string

3. The string created using the constructor new String() is of object type //string

var str1 = "javascript"; //string
var str2 = String("javascript"); //string not recommended
var str3 = new String('javascript'); //object

There is also a difference between object and string

s1 = "2 2"; // creates a string primitive
s2 = new String("2 2"); // creates a String object
console.log(eval(s1)); // returns the number 4
console.log(eval(s2)); // returns the string "2 2"
Conversion of string objects valueof -》 string

console.log(eval(s2.valueOf())); // returns the number 4

2. boolean

Do not confuse the original value true false with the Boolean object whose value is true false

1. If the parameter of the Boolean constructor is not a Boolean value, the parameter will be converted into a Boolean value

2. If the parameter is 0, -0, null, false, NaN, undefined, or an empty string (""), the value of the generated Boolean object is false. Any other value, including any object or string" false", will create a Boolean object with a value of true

var x = new Boolean(false);
if(x){
 console.log(x.valueOf(),typeof x); // false object
}
Copy after login

The above will be executed, very magical code

Do not convert a non-Boolean value into a Boolean value by creating a new Boolean object. It is correct to use the Boolean function directly

var x = Boolean(expression);  // 这样用
var x = new Boolean(expression); // 而不要这样!
初始化的时候

//false
var bNoParam = new Boolean();
var bZero = new Boolean(0);
var bNull = new Boolean(null);
var bEmptyString = new Boolean("");
var bfalse = new Boolean(false);
//true
var btrue = new Boolean(true);
var btrueString = new Boolean("true");
var bfalseString = new Boolean("false");
var bSuLin = new Boolean("Su Lin");
Copy after login

3. Number

According to the ECMAScript standard, there is only one number type in JavaScript: a double-precision 64-bit binary value (-(253 -1) to 253 -1) based on the IEEE 754 standard. It does not give a specific type for integers. In addition to being able to represent floating point numbers, there are also signed values: Infinity, -Infinity and NaN (Not-a-Number)

The numeric type has only one integer, which can be represented in two ways: 0 can be represented as -0 and 0 ("0" is the abbreviation of 0). In practice, this also has little impact. For example 0 === -0 is true. However, you may want to pay attention when dividing by 0:

42/0; // Infinity
42/-0; // -Infinity

If the argument cannot be converted to a number, NaN is returned.

In non-constructor context (i.e. without new operator), Number can be used to perform type conversion

isNAN type judgment

Number.isNaN(NaN);  // true
Number.isNaN(Number.NaN); // true
Number.isNaN(0 / 0)  // true
// e.g. these would have been true with global isNaN()
Number.isNaN("NaN");  // false
Number.isNaN(undefined); // false
Number.isNaN({});   // false
Number.isNaN("blabla"); // false
// These all return false
Number.isNaN(true);
Number.isNaN(null);
Number.isNaN(37);
Number.isNaN("37");
Number.isNaN("37.37");
Number.isNaN("");
Number.isNaN(" ");
Copy after login

原型链继承的关系

console.log(Number.prototype.__proto__ == Object.prototype); //true
console.log(Number.prototype.__proto__.__proto__ == Object.prototype.__proto__);//true
console.log(Object.prototype.__proto__ === null);//true
console.log(typeof Number);//function

使用 Number 转换 Date 对象

var d = new Date("December 17, 1995 03:24:00");
console.log(Number(d));

四、Null

null 是一个 JavaScript 字面量,表示空值(null or an "empty" value),即没有对象被呈现(no object value is present)。它是 JavaScript 原始值 之一。

null 是一个字面量 (而不是全局对象的一个属性,undefined 是 )

console.log(null); //null
console.log(undefined);//undefined
console.log(window.null);//undefined
console.log(window.undefined);//undefined

null与undefined的区别

console.log(foot);//Uncaught ReferenceError: foot is not defined
var foo;
console.log(foo);//undefined
var bar =null;
console.log(bar);//null
typeof null  // object (bug in ECMAScript, should be null)
typeof undefined // undefined
null === undefined // false
null == undefined // true
Copy after login

所以判断null,可以判断类型 + 值

五、Undefined

在JavaScript中,undefined这个词有多重含义.首字母大写的Undefined表示的是一种数据类型,小写的undefined表示的是属于这种数据类型的唯一的一个值.但这两种undefined都只能存在于文档或规范中,不能存在于JavaScript代码中.在JavaScript代码中,你看到的undefined最有可能是全局对象的一个属性,该属性的初始值是就是前面所说的原始值undefined,还有种情况就是,这个undefined是个局部变量,就像其他普通变量一样,没有任何特殊性,它的值不一定是undefined,但通常情况下都是的.下面我们所说的undefined,都指的是window.undefined这个属性.

在ES3中(Firefox4之前),window.undefined就是一个普通的属性,你完全可以把它的值改变成为任意的真值,但在ES5中((Firefox4之后),window.undefined成了一个不可写,不可配置的数据属性,它的值永远是undefined.

一个未初始化的变量的值为undefined,一个没有传入实参的形参变量的值为undefined,如果一个函数什么都不返回,则该函数默认返回undefined.

你可以使用严格相等运算符来判断一个值是否是undefined:

var foo;
console.log(foo === undefined);//true
console.log(typeof foo === 'undefined');//true
console.log(window.foo === undefined);//true
console.log(bar === undefined);//Uncaught ReferenceError: bar is not defined
console.log(typeof bar === 'undefined');//true
console.log(window.bar === undefined);//true
console.log(typeof undefined == 'undefined'); //true
console.log(typeof null == 'object');//true
console.log(null == undefined);//true
console.log(null === undefined);//false
Copy after login

总结

Null的值是null,表示一个空对象指针,没有指向任何对象
Undefined的值是undefined,表示申明变量或对象的属性却未初始化
undefined值是派生自null的,所以对他们执行相等测试会返回true
数值、布尔值、对象和字符串值都有toString()方法。但null和undefined值没有这个方法
多数情况下,调用toString()方法不必传递参数。但是,在调用数值的toString()方法时,可以传递一个参数:输出数值的基数

var num = 10;
alert(num.toString()); //"10"
alert(num.toString(2)); //"1010"
alert(num.toString(8)); //"12"
alert(num.toString(10)); //"10"
alert(num.toString(16)); //"a"

在不知道要转换的值是不是null或undefined的情况下,还可以使用转型函数String(),这个函数能够将任何类型的值转换为字符串。String()函数遵循下列转换规则:

  ● 如果值有toString()方法,则调用该方法(没有参数)并返回相应的结果

  ● 如果值是null,则返回"null"

  ● 如果值是undefined,则返回"undefined"

六、Object

Javascript中一切皆Object

// Objects
typeof {a:1} === 'object';
// 使用Array.isArray或者Object.prototype.toString.call方法可以从基本的对象中区分出数组类型
typeof [1, 2, 4] === 'object';
typeof new Date() === 'object';
// 下面的容易令人迷惑,不要这样使用!
typeof new Boolean(true) === 'object';
typeof new Number(1) ==== 'object';
typeof new String("abc") === 'object';
// 函数
typeof function(){} === 'function';
typeof Math.sin === 'function';
Copy after login

实例化一个空Object

var o = new Object();
var o = new Object(undefined);
var o = new Object(null);
var o = {};

原型

定义属性为__proto__: 值 或 "__proto__": 值 时,不会创建名为__proto__属性。如果给出的值是对象或者null,那么对象的[[Prototype]]会被设置为给出的值。(如果给出的值不是对象也不是null,那么对象的原型不会改变。)

var obj1 = {};
assert(Object.getPrototypeOf(obj1) === Object.prototype);
var obj2 = { __proto__: null };
assert(Object.getPrototypeOf(obj2) === null);
var protoObj = {};
var obj3 = { "__proto__": protoObj };
assert(Object.getPrototypeOf(obj3) === protoObj);
 var obj4 = { __proto__: "not an object or null" };
assert(Object.getPrototypeOf(obj4) === Object.prototype);
assert(!obj4.hasOwnProperty("__proto__"));
Copy after login

在对象字面值中,仅有一次变更原型的机会;多次变更原型,会被视为语法错误。

不使用冒号记法的属性定义,不会变更对象的原型;而是和其他具有不同名字的属性一样是普通属性定义。

var __proto__ = "variable";
var obj1 = { __proto__ };
assert(Object.getPrototypeOf(obj1) === Object.prototype);
assert(obj1.hasOwnProperty("__proto__"));
assert(obj1.__proto__ === "variable");
var obj2 = { __proto__() { return "hello"; } };
assert(obj2.__proto__() === "hello");
var obj3 = { ["__prot" + "o__"]: 17 };
assert(obj3.__proto__ === 17);
Copy after login

与JSON的区别

JSON 只允许"property": value syntax形式的属性定义。属性名必须用双引号括起来。且属性定义不允许使用简便写法。
JSON中,属性的值仅允许字符串,数字,数组,true,false,或者其他JSON对象。
JSON中,不允许将值设置为函数。
Date 等对象,经JSON.parse()处理后,会变成字符串。
JSON.parse() 不会处理计算的属性名,会当做错误抛出。

defineProperty

Object.defineProperty() 方法直接在一个对象上定义一个新属性,或者修改一个已经存在的属性, 并返回这个对象
// 使用 __proto__
Object.defineProperty(obj, "key", {
 __proto__: null, // 没有继承的属性
 value: "static" // 没有 enumerable
     // 没有 configurable
     // 没有 writable
     // 作为默认值
});
// 显式
Object.defineProperty(obj, "key", {
 enumerable: false,
 configurable: false,
 writable: false,
 value: "static"
});
// 回收同一对象
function withValue(value) {
 var d = withValue.d || (
 withValue.d = {
  enumerable: false,
  writable: false,
  configurable: false,
  value: null
 }
 );
 d.value = value;
 return d;
}
// ... 和 ...
Object.defineProperty(obj, "key", withValue("static"));
// 如果 freeze 可用, 防止代码添加
// value, get, set, enumerable, writable, configurable
// 到对象原型上
(Object.freeze||Object)(Object.prototype);
Copy after login

configurable当且仅当这个属性描述符值为 true 时,该属性可能会改变,也可能会被从相应的对象删除。默认为 false。

enumerabletrue 当且仅当该属性出现在相应的对象枚举属性中。默认为 false。

value 与属性相关的值。可以是任何有效的 JavaScript 值(数值,对象,函数等)。默认为 undefined。

writable true 当且仅当可能用 赋值运算符 改变与属性相关的值。默认为 false。

存取描述符同时具有以下可选键值:

get 一个给属性提供 getter 的方法,如果没有 getter 则为 undefined。方法将返回用作属性的值。默认为 undefined。
set 一个给属性提供 setter 的方法,如果没有 setter 则为 undefined。该方法将收到作为唯一参数的新值分配给属性。默认为 undefined。

ps:js中的变量定义

在JavaScript中,使用var来定义任何类型的变量,每一个变量只是用于保存数据的占位符。

var temp; //这句代码定义了一个变量,但其类型是未知的,可以存放任何类型的值,没有初始化的时候,test中存储是undefined。
var temp=2; //这句代码定义了一个变量,并直接初始化为数值型。
var temp="javascript"; // 这句代码定义了一个变量,并直接初始化微string型,单引号和双引号都可以,只要成对出现就行。

2、变量的作用域

在Javascript中,使用var定义的变量,其作用域是在定义该变量的方法或函数内。也就是说,使用var定义的变量是局部变量。
例:

function test()
{
 var temp="Hello, Javascript!";
}

test(); //方法调用的时候创建变量并初始化,执行结束后变量被销毁。
alert(temp); //undefined。因为变量temp已经被销毁,所以是未定义(undefined)。

如果在定义变量时,不使用var,那么定义的变量是全局变量。

例:

function test2() 
 { 
  temp2="Hello, Javascript!"; 
 } 
test2(); //调用方法时,创建变量并初始化,执行结束后变量依然存在。 
alert(temp2); //Hello, Javascript! 变量值依然存在 
Copy after login

以上内容是小编给大家介绍的Javascript中的数据类型之旅,希望大家喜欢。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!