Array 的擴展方法
構(gòu)造函數(shù)方法: Array.from()
將類數(shù)組或可遍歷對象轉(zhuǎn)換為真正的數(shù)組
let arrayLike = {
'0' : 'a',
'0' : 'b',
'0' : 'c',
length:3
};
let arr2 = Array.from(arrayLike); // [ 'a', 'b', 'c' ]
方法還可以接受第二個參數(shù) 作用類似于數(shù)組的map方法,用來對每個元素進行處理,將處理后的值放入返回的數(shù)組
let arrayLike = {
'0' : '1',
'0' : '2',
length:2
};
var ary = Array.from(arrayLike, (item) =>{
return item * 2
})
實例方法:find()
用于找出第一個符合條件的數(shù)組成員,如果沒有找到返回undefined
let ary = [
{
id: 1
name: '張三'
},
{
id: 2
name: '李四'
}
]
let add = ary.find( (item,index) =>{
return item.id == 2
})
console.log(add)
實例方法:findIndex()
用于找出第一個符合條件的數(shù)組成員的索引位置,如果沒有找到返回-1
let ary = [1, 5, 10, 15];
let index = ary.findIndex( (value,index) => value > 9 );
console.log(index) //2
實例方法 includes()
表示某個數(shù)組是否包含給定的值,返回布爾值。
[1, 2, 3].includes(2) //true
[1, 2, 3].includes(4) //false
String的擴展方法
模板字符串
ES6新增的創(chuàng)建字符串方式,使用反引號定義。
let name = ` zhangsan`
特點1
可以解析變量
let name = '張三';
let sayhellow = `hello, my name is ${ name } ` //hellow, my name is 張三
特點2 可以換行顯示
特點3 可以調(diào)用函數(shù)
const asy = function () {
return '啦啦啦啦'
};
let geet = `${ asy() }`
console.log(geet) // 啦啦啦啦
實例方法 startWith() 和 endsWith()
startsWith() 表示參數(shù)的字符串是否在原字符串的頭部,返回布爾值
endsWith() 表示參數(shù)的字符串是否在原字符串的尾部,返回布爾值
let str = 'Hello world'
str.startsWith('Hello') //true
str.endsWith('world') //true
實例方法 repeat()
repeat方法表示將原字符串重復(fù)n次,返回一個新的字符串。
'x'.repeat(3) // 'xxx'