数字,字符串,对象

var length = 16;                               // Number
var lastName = “Johnson”;                      // String
var x = {firstName:“John”, lastName:“Doe”};    // Object

相加:

var x = 16 + 4 + “Volvo”;

结果:

20Volvo

var x = “Volvo” + 16 + 4;

结果:

Volvo164

数组:

var cars = [“Saab”, “Volvo”, “BMW”];

undefined

car = undefined;    // Value is undefined, type is undefined

var car;    // Value is undefined, type is undefined

Empty 

var car = “”;    // The value is “”, the typeof is “string”

null

var person = {firstName:“John”, lastName:“Doe”, age:50, eyeColor:“blue”};
person = null;    // Now value is null, but type is still an object

Undefined Null 异同:

undefined and null are equal in value but different in type:

typeof undefined// undefined

typeof null// object

null === undefined// false

null == undefined// true

基本数据类型

A primitive data value is a single simple data value with no additional properties and methods.

The typeof operator can return one of these primitive types:

  • string
  • number
  • boolean
  • undefined

Example

typeof “John”// Returns “string”

typeof 3.14// Returns “number”

typeof true // Returns “boolean”

typeof false // Returns “boolean”

typeof x // Returns “undefined” (if x has no value)

对象(javascript的对象就是键值对):

var staffInfo ={name:“christopher”,gender:“male”,tech:“coding”};

staffInfo

{name: “christopher”, gender: “male”, tech: “coding”}

gender: “male”

name: “christopher”

tech: “coding”

__proto__: Object

 

使用key,要带引号:

staffInfo[“gender”]

“male”

staffInfo[gender]

Uncaught ReferenceError: gender is not defined

 

带函数的对象

var simple = {
        pro:"hello",
        myMethod: function(){
                console.log("my method was called")
                }
}

simple

{pro: "hello", myMethod: ƒ}
myMethod: ƒ ()
pro: "hello"
proto: Object

console.dir(simple)

myMethod: ƒ ()
pro: "hello"
proto: Object

simple.myMethod,不加括号,显示的是函数

ƒ (){
console.log("my method was called")
}

simple.myMethod(),加括号,调用函数

 my method was called
var myObj = {

     name : "chris",
     greet: function(){

         console.log("hello " + this.name);
      }
}

查看,myObj

{name: "chris", greet: ƒ}                
greet: ƒ ()
name: "chris"
proto: Object

查看属性,myObj[‘name’]

 "chris"

调用函数,myObj.greet()

 hello chris 



发表评论

电子邮件地址不会被公开。 必填项已用*标注