1、将一个元素插入到现有数组的特定索引处
// 原来的数组
var array = ["one", "two", "four"];
// splice(position, numberOfItemsToRemove, item)
// 拼接函数(索引位置, 要删除元素的数量, 插入的元素)
array.splice(2, 0, "three");
array; // 现在数组是这个样子 ["one", "two", "three", "four"]
可以把这个插入函数写入到你的原生环境当中
Array.prototype.insert = function(index,item){ //插入位置的index,后需要插入的元素item
this.splice(index,0,item);
}
这样的话可以这样调用
var nums = ["one", "two", "four"];
nums.insert(2, 'three'); // 注意数组索引, [0,1,2..]
array // ["one", "two", "three", "four"]
2、实现空数组
bad的做法
myArray = []; // bad
good的做法
myArray.length=0; // bad
为啥啊 因为bad的做法完全,看例子
A = [1,2,3,4,5]
B = A
A = []
console.log(B) // [1,2,3,4,5]
3、sort排序
// 看上去正常的结果:
['Google', 'Apple', 'Microsoft'].sort(); // ['Apple', 'Google', 'Microsoft'];
// apple排在了最后:
['Google', 'apple', 'Microsoft'].sort(); // ['Google', 'Microsoft", 'apple']
// 无法理解的结果:
[10, 20, 1, 2].sort(); // [1, 10, 2, 20]
第二个排序把apple排在了最后,是因为字符串根据ASCII码进行排序,而小写字母a的ASCII码在大写字母之后。
第三个排序结果是什么鬼?简单的数字排序都能错?
这是因为Array的sort()方法默认把所有元素先转换为String再排序,结果'10'排在了'2'的前面,因为字符'1'比字符'2'的ASCII码小。
所以一般不采用默认排序,而是采用高级函数作为参数
var arr = [10, 20, 1, 2];
arr.sort((x,y)=>x-y);
console.log(arr); // [1, 2, 10, 20]