ECMAScript 6(ES6) 特性概覽和與ES5的比較17-數組和字符串的新內置方法

1.對象屬性賦值

用於將一個或多個源對象的可枚舉屬性分配到目標對象的新函數。

Object.assign() 對象合併函數,重複的會被右邊的替換

ECMAScript 6

var dest = { quxx: 0 }
var src1 = { foo: 1, bar: 2 }
var src2 = { foo: 3, baz: 4 }
Object.assign(dest, src1, src2)
dest.quux === 0
dest.foo === 3
dest.bar === 2
dest.baz === 4

ECMAScript 5

var dest = { quxx: 0 };
var src1 = { foo: 1, bar: 2 };
var src2 = { foo: 3, baz: 4 };
Object.keys(src1).forEach(function(k) {
    dest[k] = src1[k];
});
Object.keys(src2).forEach(function(k) {
    dest[k] = src2[k];
});
dest.quux === 0;
dest.foo === 3;
dest.bar === 2;
dest.baz === 4;

2.數組元素查找

在數組中找到一個元素的新方法

[].find()

[].findIndex()

ECMAScript 6

[ 1, 3, 4, 2 ].find(x => x > 3) //4
[ 1, 3, 4, 2 ].findIndex(x => x > 3) //2

ECMAScript 5

[ 1, 3, 4, 2 ].filter(function(x) { return x > 3; })[0]; //4
//ES中沒有相應表達

3.字符串重複

新的字符串重複函數

“”.repeat(number) //number是重複次數

ECMAScript 6

" ".repeat(4* depth)
"foo".repeat(3) // foofoofoo

ECMAScript 5

Array((4 * depth) + 1).join(" ");
Array(3 +1).join("foo");

4.字符串搜索

用於搜索子字符串的新特定字符串函數。

ECMAScript 6

"hello".startsWith("ello", 1)  //true
"hello".endsWith("hell", 4)  // true
"hello".includes("ell") // true
"hello".includes("ell", 1) // true
"hello".includes("ell", 2) // false

ECMAScript 5

"hello".indexOf("ello") === 1; //true
"hello".indexOf("hell") === (4-"hell".length); //true
"hello".indexOf("ell") !== -1; //true
"hello".indexOf("ello", 1) !== -1; //true
"hello".indexOf("ello", 2) !== -1; //true
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章