Home  >  Article  >  Web Front-end  >  Javascript Study Notes 1 Data Type_Basic Knowledge

Javascript Study Notes 1 Data Type_Basic Knowledge

WBOY
WBOYOriginal
2016-05-16 18:13:43927browse
1. Data types
Javascript is a weakly typed scripting language. It has a total of 6 data types, which are divided into basic data types, special data types, and composite data types.
1. Basic data types: numeric, string, Boolean
2. Special data types: null, undefined (the difference is that null requires explicit assignment, while undefined means no assignment)
3. Composite (reference) data type: Object (array is a special object)

Note: Understand the difference between basic data types and reference data types. Such as function parameter passing

2. The relationship between packaging classes and basic data types
For basic data types, there are corresponding packaging classes (Object objects) corresponding to them.
Number, String, Boolean

Note: Basic data types will be converted into basic type packaging objects under certain conditions
Copy code The code is as follows:

var str="This is a basic string";
var length=str.length();
//When using length (), the Javascript interpretation engine will generate
//a temporary String object of str. After execution, the temporary object will be cleared

3. How to determine the data type
(1) typeof (tasteless)
Only the following 6 data types can be detected: number, string, boolean, undefined, object, function (note!)
Copy code The code is as follows:

alert(typeof(null)); //The result is object
alert(typeof(a)); // a is not assigned, the result is undefined

Therefore, the basic data type can be determined as follows:
Copy code The code is as follows:

function type(o) {
return (o === null) ? 'null' : typeof(o);
}

(2) instanceof
  But for composite data types (except function), all return objects, which cannot be judged by typeof
You can use instanceof to detect whether an object is an instance of another object. Pay attention to the right side of instanceof. The operand must be an object:
Copy code The code is as follows:

function Animal() {} ;
function Pig() {};
Pig.prototype = new Animal();
alert(new Pig() instanceof Animal); // true

instanceof does not Suitable for detecting the type of an object itself

(3) constructor
Copy code The code is as follows:

alert(1.constructor); // Error reporting
var o = 1;
alert(o.constructor); // Number
o = null; // or undefined
alert(o.constructor); // Error reporting
alert({}.constructor); // Object
alert(true.constructor); // Boolean

(4 ) Object.toString()
Copy code The code is as follows:

function isArray(o) {
return Object.prototype.toString.call(o) === '[object Array]';
}


The difference between call and apply:
They They are all methods of Function.prototype (for methods), which are implemented internally by the Javascript engine.
In fact, the functions of these two are almost the same. What should be noted is that the arg parameter in call(thisObj[,arg1[, arg2[,)) can be a variable, while apply([thisObj[,argArray]] ) is an array collection
The method is lent to the call of another object to complete the task. In principle, the context object changes when the method is executed.

(5) Summary
Copy code The code is as follows:

var _toS = Object.prototype.toString,
_types = {
'undefined' : 'undefined',
'number' : 'number',
'boolean' : 'boolean',
'string' : 'string',
'[object Function]' : 'function',
'[object RegExp]' : 'regexp',
'[object Array]' : 'array',
'[object Date]' : 'date',
'[object Error]' : 'error'
};

function type(o) {
return _types[typeof o] || _types[_toS.call(o)] || ( o ? 'object' : 'null');
}

4. 데이터 유형 변환
자바스크립트에는 두 가지 데이터 유형 변환 방법이 있습니다.
하나는 전체 값을 한 유형에서 다른 데이터 유형으로 변환하는 것입니다(기본 데이터 유형 변환이라고 함).
또 다른 방법은 하나의 값에서 다른 유형의 값을 추출하여 변환 작업을 완료하는 것입니다.
세 가지 기본 데이터 유형 변환 방법이 있습니다.
1. 문자 유형으로 변환: String(); 예: String(678)의 결과는 "678"입니다.
2. 숫자 유형으로 변환: Number (); 예: Number("678")의 결과는 678
3. Boolean 유형으로 변환: Boolean(); 예: Boolean("aaa")의 결과는 true
값에서 추출 또 다른 유형의 값은 다음과 같습니다.
1. 문자열에서 정수를 추출합니다:parseInt(); 예:parseInt("123zhang")의 결과는 123입니다.
2. 문자열에서 부동소수점을 추출합니다. :parseFloat(); 예:parseFloat("0.55zhang")의 결과는 0.55입니다

 
또한 다양한 유형 변환 방법을 요약합니다


숫자가 변환됩니다. 문자열로 :String(number),
Number.toString(2/8/16);//2진수, 8진수, 16진수, 기본(매개변수 없음) 10진수,
toFixed(3) //10진수 유지 point 마지막 3자리
toExponextial(3); // 소수점 앞 1자리, 소수점 뒤 3자리 예: n.toExponextial(3); 🎜> toPrecision(4) ; //지정된 자릿수를 반환합니다. 자릿수가 완전히 표시되지 않으면 지수 표기법을 사용합니다(세 가지 방법 모두 4에서 5로 반올림됨)

5. 기타 요약( 간과하기 쉬운 것)
1.parseInt의 함정
다음 부분은 "Javascript Essence"에서 발췌합니다.
parseInt는 문자열을 정수로 변환하는 함수입니다. 숫자가 아닌 값을 발견하면 구문 분석을 중지하므로,parseInt("16")는parseInt("16tons")와 동일한 결과를 생성합니다. 함수가 추가 텍스트가 있다는 것을 알려주면 좋겠지만 그렇지 않습니다.
문자열의 첫 번째 문자가 0이면 문자열은 10진수가 아닌 8진수를 기준으로 평가됩니다. 8진수에서 8과 9는 같은 숫자가 아니므로,parseInt("08")와parseInt("09")는 결과적으로 0을 생성합니다. 이 버그는 프로그램이 날짜와 시간을 구문 분석할 때 문제를 일으킵니다. 다행히도,parseInt는 기수를 인수로 받아들일 수 있으므로,parseInt("08",10)은 8을 반환합니다. 항상 이 기수 인수를 제공하는 것이 좋습니다.
또한. 다음은 1을 표시합니다:
 
alert(parseInt(0.0000001))
이는 js가 특정 정밀도를 초과하는 경우 숫자를 기록하기 위해 과학적 표기법을 사용하기 때문입니다. 예:
 
Alert(0.0000001 );
은 1e-7을 가져오고,parseInt는 자동으로 매개변수를 문자열로 변환합니다. 이는
 

코드 복사 코드는 다음과 같습니다.
s = (0.0000001).toString()
alert(parseInt(s));
드디어 1등을 한 것도 놀랍지 않습니다.
parseInt를 사용할 때 매개변수가 문자열로 변환된 후 변환된다는 점을 기억해야 합니다.
Statement:
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