ReactNative的語法基礎(chǔ)要求JS,JSX,ES6.其中ES6是這三種語法的核心.系統(tǒng)學(xué)習(xí)ES6的語法是ReactNative編程的基本要求.下面記錄ES6的典型語法的示例,以方便編程中的隨時(shí)查用.
1定義變量, 關(guān)鍵字const, var, let. let定義的變量,作用域?yàn)榇a塊;var定義的變量,作用域能穿透后面代碼塊;const修改的變量不可修改;
let a = 1;
var b = 'string';
const c = 2;
let和var在for循環(huán)使用中的區(qū)別:
var a = [];
for (let i = 0; i < 10; i++) {
a[i] = function () {
console.log(i);
};
}
a[6](); // 6
var a = [];
for (var i = 0; i < 10; i++) {
a[i] = function () {
console.log(i);
};
}
a[6](); // 10
2變量的解構(gòu)賦值.對(duì)變量復(fù)制時(shí),當(dāng)?shù)忍?hào)左邊定義的變量和等號(hào)右邊的賦值形式一致時(shí),能夠?qū)ψ兞孔詣?dòng)賦值;
let {a, b} = {a:"x", b:"y"};
//a = x, b = y;
let [a, b] = [0, 1, 2, 3];
//a=0, b = 1;
let [a, ...b] = [0, 1, 2, 3];
//a=0, b = [1,2,3];
3操作字符串.
(1)遍歷
for(i of 'hello') {
console.log(i);
}
//
[info][tid:com.facebook.react.JavaScript] h
[info][tid:com.facebook.react.JavaScript] e
[info][tid:com.facebook.react.JavaScript] l
[info][tid:com.facebook.react.JavaScript] l
[info][tid:com.facebook.react.JavaScript] o
(2)引用
var a = 'hello'
var ch = a.charAt(1);
console.log(ch);
//e
(3)判斷
var a = 'hello'
a.startsWith('he')//true
a.startsWith('lo')//true
a.includes('ll')//true
(4)引用(使用右上頓號(hào))
var a = 'Hello'
console.log(`${a} world!`)
4操作數(shù)值
(1)判斷
//是否是非無窮大
Number.isFinite(15)//true
Number.isFinite('a')//true
Number.isFinite(NaN)//false
//是否是整數(shù)
Number.isInteger(15)//true
Number.isInteger('15')//false
(2)轉(zhuǎn)化
Number.parseInt("12.34") // 12
Number.parseFloat('123.45#') // 123.45
(3)Math應(yīng)用
//去除小數(shù)部分
Math.trunc(1.2)//1
Math.trunc(-1.2)//-1
//數(shù)字符號(hào),正數(shù)為+1,負(fù)數(shù)為-1,0位0
Math.sign(-1)//-1
Math.sign(1)//+1
Math.sign(0)//0
5操作數(shù)組
(1)創(chuàng)建
var arr = ['a', 'b', 'c'];
var arr1 = Array.from('a', 'b', 'c');//['a', 'b', 'c']
var arr2 = Array.from({ 0: "a", 1: "b", 2: "c"});//['a', 'b', 'c']
var arr3 = Array.of('a', 'b', 'c')//['a', 'b', 'c']
(2)查找
var arr = [0, 1, 2, 3];
//返回第一個(gè)滿足條件的值
var result = arr.find((value, index, arr) => {
return value > 1;
})
console.log(result);//2
//返回第一個(gè)滿足條件值的索引
var resultIndex = arr.findIndex((value, index, arr) => {
return value > 2;
});
console.log(resultIndex);//3
(3)遍歷
for (let index of ['a', 'b'].keys()) {
console.log(index);
}
// 0
// 1
for (let elem of ['a', 'b'].values()) {
console.log(elem);
}
// 'a'
// 'b'
for (let [index, elem] of ['a', 'b'].entries()) {
console.log(index, elem);
}
// 0 "a"
// 1 "b"
6操作對(duì)象
(1)定義
var obj = {
name: 'Lily',
speak(){
console.log(`My name is `+ this.name);
}
}
obj.speak();//My name is Lily
(2)添加屬性和方法
obj['age'] = 10;
console.log(obj['age']);
obj.speakAge = function(){
console.log('My age is ' + this.age);
}
obj.speakAge();
7定義函數(shù)
(1)一般定義方式
function foo() {
console.log('first function');
}
(2)簡(jiǎn)化定義方式(ES6推薦寫法)
var foo = () => {
console.log('another function');
}
(3)函數(shù)的rest參數(shù)
var foo = (x, y, ...z) => {
console.log(x, y, z);
}
foo(1,2,3,4,5);
//1, 2, [ 3, 4, 5 ]
8Set和Map數(shù)據(jù)類型
類似OC中的NSSet和NSDictionary,是ReactNative中兩種常用的基本數(shù)據(jù)類型.
(1)Set能保證里面元素的唯一性
>1 定義
let setOne = new Set();
//接受數(shù)組參數(shù)
let setTwo = new Set([0, 1, 2, 2]);//[0, 1, 2]
>2 屬性和方法
setTwo.size;//3 獲取元素個(gè)數(shù)
setTwo.add(3);//添加
setTwo.delete(3);//刪除
setTwo.has(2);//true查找
>3 遍歷
for (i of setTwo.keys()) {
console.log('keys: ' + i);
}
for (i of setTwo.values()) {
console.log('values: ' + i);
}
for ([key, value] of setTwo.entries()) {
console.log('key: ' + key + ' value ' + value);
}
//
keys: 0
keys: 1
keys: 2
values: 0
values: 1
values: 2
key: 0 value 0
key: 1 value 1
key: 2 value 2
(2)Map是key和value一一對(duì)應(yīng)的鍵值對(duì)
>1定義
let m = new Map();
let m2 = new Map([['name', 'Lily'], ['age', 10]]);
>2屬性和方法
m2.get('name');//Lily
m2.set('name', 'Json');
m2.size;//2
m2.has('name');//true
m2.delete('name');//true
m2.clear();
//
keys: name
keys: age
values: Lily
values: 10
key: name value Lily
key: age value 10
9Generator函數(shù)
通過在函數(shù)名前添加*和在方法中添加yield關(guān)鍵字來定義,控制函數(shù)的順序執(zhí)行.
function *genFun() {
yield 'Lily';
yield 'Json';
return 'Niu';
}
let gen = genFun();
genFun().next();//{value: 'Lily', done: false}
genFun().next();//{value: 'Json', done: false}
genFun().next();//{value: 'Niu', done: true}
//可以使用for of 語句來遍歷
for (i of gen) {
console.log(i);
}
//return后的元素,不會(huì)被遍歷到
Lily
Json
10Promise對(duì)象
通過定義Promise和關(guān)鍵字then的結(jié)合,可以方便實(shí)現(xiàn)函數(shù)的成功回調(diào)和失敗回調(diào).
(1)定義
var prom = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('download success')
resolve('success');
}, 1000);
});
prom.then((flag) => {
console.log('success block:' + flag);
}, (error) => {
console.log('failure block:' + error);
})
(2)async關(guān)鍵字和Promise實(shí)例相結(jié)合,實(shí)現(xiàn)多個(gè)異步線程的順序執(zhí)行;
async function foo() {
await new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, 5000);
});
console.log('await function completed');
}
foo();
//打印消息會(huì)在5s后resolve回調(diào)執(zhí)行后,才執(zhí)行;
11Class和Module
弱模塊一直是JS令人詬病的地方.現(xiàn)在ES6中,可以通過import命令,可以方便引用其他Module.
<1>class的定義
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
set personName(name) {
this.name = name;
}
get personName() {
return this.name;
}
speak() {
console.log(`My name is ${this.name}, my age is ${this.age}`);
}
}
<2>class的繼承
class Student extends Person {
constructor(name, age, grade) {
super(name, age);
this.grade = grade;
}
speak() {
super.speak();
console.log(`My grade is ${this.grade}`);
}
}
<3>class的靜態(tài)方法
class Person {
static eat() {
console.log('I eat every day!');
}
}
Person.eat();
module模塊的導(dǎo)入
//person.js文件
export var firstName = 'Json';
export var secondName = 'Frank';
export var age = 18;
export default function speak () {
console.log('I am a Person');
}
//main.js文件中導(dǎo)入
import speak, {firstName, secondName, age} from './person';
//將對(duì)象導(dǎo)出,只需要在前面加上關(guān)鍵字export即可.由于export default默認(rèn)導(dǎo)出的設(shè)置,speak名字可以不同,如下:
import speakAnother, {firstName, secondName, age} from './person';
以上語法是結(jié)合對(duì)項(xiàng)目進(jìn)行ReactNative改造后,總結(jié)出來的需要掌握的基本語法.掌握以上語法,對(duì)一個(gè)簡(jiǎn)單ReactNative項(xiàng)目,能夠更快理解和上手操作,希望幫助到需要的小伙伴.
以上內(nèi)容均節(jié)選自電子書ES6新語法,繼續(xù)深入學(xué)習(xí),可以詳細(xì)翻閱.
喜歡和關(guān)注都是對(duì)我的支持和鼓勵(lì)~