一.数组方法
之前的方法都是在原数组上做修改(改变了原数组);以下的方法是新建一个数组(原数组不改变,即可以在原数组上无限使用下面方法):
1.contact
var arr1 = ['a', 'b', 'c'];
var arr2 = ['d', 'e', 'f'];
var arr3 = arr1.contact(arr2);
console.log(arr3); /输出['a', 'b', 'c', 'd', 'e', 'f']
contact:新建一个数组,整合它们。
a.contact(b) : 整合a,b。 a在前 b在后
2. toString()
arr1.toString() :将数组转化成字符串
3. slice
arr.slice(a, b) : 从下标index = a的地方开始截取到 index = b 的位置之前。
var a = ['d', 'e', 'f'];
var b = a.slice(0, 2);
console.log(b); // ["d", "e"]
负数从后往前数,倒数第一个为-1 ,倒数第二个为-2 :
var a = ['d', 'e', 'f'];
var b = a.slice(-3,2);
console.log(b); // ["d", "e"]
/可以在原数组上无限使用下面方法:
var c = a.slice(-3,-2);
console.log(c); / ["d"]
可以在原数组上无限使用下面方法
只有一个参数时,默认从该参数开始一直数到该数组的最后一位;
var a = ['d', 'e', 'f'];
var b = a.slice(1);
console.log(b); // ["e", "f"]
没有参数时,默认从第一位开始一直数到该数组的最后一位,即输入整个数组
4. join
将数组转为字符串,并可用括号内参数分割。 如果没有参数,默认将字符串用逗号分隔
5.split: 将字符串分隔成数组
join和split通常一起使用:
split(' join中分隔的参数', 截取数组的长度)
split的第一个参数必须和join中的参数一致,不然没有效果
<script>
var arr = ['a', 'b', 'c'];
var str1 = arr.join('-');
console.log(str1); /a-b-c
var arr1 = str1.split('-', 2)
console.log(arr1);/["a", "b"]
</script>
如果没有join: 那么第一个参数就应该填空:
var arr = 'abcdefg';
var arr1 = arr.split('', 5)
console.log(arr1); /["a", "b", "c", "d", "e"]
二.类数组
类数组并不是真正的数组,它是类似于数组的对象
并没有继承Array.prototype ,不能使用push()方法等。
var obj = {
'0' : 1,
'1' : 2,
'2' : 3,
'length' : 6,
'splice' : Array.prototype.splice /添加Array里面的属性,让其F12后 包围从{}变为 []
'push' : Array.prototype.push, /添加push方法,从此 此类数组就能使用push方法
}
Object.prototype.push = Array.prototype.push /同时也能在原型链里面传方法、属性
因为可以添加方法,所以类数组的优点就是既有对象的属性又有方法的属性
类数组一定要数组形式下标对应的值(如:'0' : 1,)、一定要有length属性
类数组面试题
<script>
var obj = {
'2': 3,
'3': 4,
'length': 2,
'splice': Array.prototype.splice,
'push': Array.prototype.push,
}
obj.push(1);
obj.push(2);
console.log(obj); /输出 Object(4) [empty × 2, 1, 2, splice: ƒ, push: ƒ]
</script>
push(a):在数组最后一位添加a元素
所以第三位 添加 1
第四位添加 2
注意:push(a)中的a 是index值,从0开始
所以 类数组中 长度变为4,第三项、第四项变为 1 、 2。 第一二项添加0
这个类数组 题目 最大的亮点是 '2': 3, '3': 4, 直接最后两项赋值
类数组中push的原理:
Array.prototype.push = function(elem){
this[this.length] = elem;
this.length++;
}
三. 实战
重写数组的原型上的unshift方法 :
将类数组转化为数组: Array.prototype.slice.call(arguments)
2.arguments小知识点
arguments是类数组:类似于数组的对象, typeof()后返回object