>  기사  >  웹 프론트엔드  >  JavaScript의 데이터 유형은 무엇입니까?

JavaScript의 데이터 유형은 무엇입니까?

yulia
yulia원래의
2018-09-12 16:38:441713검색

많은 JavaScript 초보자에게 데이터 유형은 혼란스럽고 때로는 사람들을 미치게 만들기도 합니다. 이제 모두를 위해 이 혼란을 해결해 보겠습니다.

JavaScript에는 총 8가지 데이터 유형이 있습니다. 여기에는 기본 데이터 유형과 참조 데이터 유형이 포함됩니다. 기본 데이터 유형은 문자열, 숫자, 부울, null, 정의되지 않음입니다. 그 중 참조 유형은 배열, 함수 및 객체입니다. 총 8개의 데이터 유형이 있으며 각 유형에는 고유한 속성이나 메소드가 있으므로 풍부하고 다채로운 JavaScript 세계가 구축됩니다.

const strA = 'xxx==='
const numberB = 123
const boolC = false

const nullD = null
const undedfinE = undefined

const arrayF = [1,2,3]
const funcG = function() {
    let a = '123'
    console.log(a)
}
const objH = {
    a: 1,
    getName: function() {
        console.log(this.a)
    }
}
const result = function(x) {
    return typeof x
}
console.log(result(strA)) // string
console.log(result(numberB)) // number
console.log(result(boolC)) // boolean
console.log(result(nullD)) // object
console.log(result(undedfinE)) // undefined
console.log(result(arrayF)) // object
console.log(result(funcG)) // function
console.log(result(objH)) // object

쉽게 혼동되는 데이터 유형 구별

TIPS: 위의 8가지 데이터 유형을 읽은 후 읽어보세요. 데이터에는 Null, Array, Object의 세 가지 유형이 있다는 사실이 아직도 다소 혼란스럽나요? 이 세 가지 데이터 유형의 유형은 객체입니다. 그럼 다시 구별하는 방법은 무엇일까요?

typeof null         // object
typeof [123,133]    // object
typeof {a:1}        // object
// 这个时候就无法判断了, 如何操作了?
const testArray = [11,22,33,44]
const testNull = null
const testObj = {a:1}
const testObjectFun = function(x) {
    return Object.prototype.toString.call(x)
}
console.log( testObjectFun(testArray))  // [object Array]
console.log( testObjectFun(testNull))   // [object Null]
console.log( testObjectFun(testObj))    // [object Object]

현재 Object.prototype.toString.call(xxx)은 현재 개체가 무엇인지 확인하는 좋은 방법입니다.

현재 객체가 배열인지 확인하는 방법

const arr = [1,2,3]
// es6
Array.isArray(arr)
arr instanceof Array
arr.constructor === Array
// es5
Object.prototype.toString.call(arr) === '[object Array]'

요약: JS 언어에서는 공통된 데이터 유형이 만들어졌습니다. 위 화면에는 현재 데이터 유형을 결정하는 몇 가지 방법도 나와 있습니다. JS는 약한 유형의 언어이므로 소위 약한 유형의 언어는 실제로 컨텍스트의 변화에 ​​따라 데이터 유형이 변경될 수 있음을 의미합니다.

위 내용은 JavaScript의 데이터 유형은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.