數(shù)組方法
var data = [15,78,'hello','world']
1,增
- // 在數(shù)組最后追加一個(gè)或多個(gè)元素,改變?cè)瓟?shù)組
data.push(123);
console.log(data);
// [15, 78, "hello", "world", 123]
- // 在數(shù)組開頭添加一個(gè)或多個(gè)元素
data.unshift(111);
console.log(data);
// [111, 15, 78, "hello", "world"]
2,刪
- // 刪除數(shù)組的最后一個(gè)元素
data.pop();
console.log(data);
// [15, 78, "hello"]
- // 刪除數(shù)組的第一個(gè)元素
data.shift();
console.log(data);
// [78, "hello", "world"]
- // 刪除數(shù)組中的某一項(xiàng),并返回被刪除的元素
// splice(index,count),index要?jiǎng)h除的索引橡淆,count要?jiǎng)h除的數(shù)量
data.splice(-2,1) //var item = data.splice(-2,1)
console.log(data); //console.log(item)
// [15, 78, "world"] //['hello']
3,改
- // 翻轉(zhuǎn)數(shù)組
data.reverse();
console.log(data);
// ["world", "hello", 78, 15]
- // 數(shù)組排序
data.sort(function(a,b){return a-b});
console.log(data);
- // 把數(shù)組轉(zhuǎn)換為字符串,返回一個(gè)字符串
var str = data.toString();
console.log(str);
// 15,78,hello,world
- // 把所有元素放入一個(gè)字符串馍惹,通過制定分隔符進(jìn)行分隔
var str = data.join(',');
console.log(str);
// 15,78,hello,world
- // 連接兩個(gè)或多個(gè)數(shù)組
var str = [111,111]
var result = data.concat(str);
console.log(result);
// [15, 78, "hello", "world", 111, 111]
4吗铐,查
- // 從某個(gè)已有數(shù)組中查詢所需數(shù)據(jù),并返回一個(gè)新數(shù)組
data.slice(start,end)
- // start開始的索引(必填)息楔,結(jié)束的索引(選填)
var str = data.slice(2);
console.log(str);
// ["hello", "world"]
4妒峦,常用方法
快速生成0-n數(shù)組
[...new Array(n).keys()]