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

猜你喜欢

转载自blog.csdn.net/u010622874/article/details/84068973