const arr = [1, 3, 4, 5, 6, 7, 8];
const newArr = arr;
console.log(`arr: ${arr}`); // arr: 1,3,4,5,6,7,8
console.log(`newArr: ${newArr}`); // arr: 1,3,4,5,6,7,8
// 原数组改变,新数组也会跟着改变,因为这里的是浅复制,仅仅是point指向arr
arr.length = 4;
console.log(`arr: ${arr}`); // arr: 1,3,4,5
console.log(`newArr: ${newArr}`); // newArr: 1,3,4,5
const arr = [1, 3, 4, 5, 6, 7, 8];
const newArr = arr.map(arr=>arr); // map 会输出一个新的数组
// const newArr = [...arr]; // 用es6的spread 传播的扩展数组方式形成一个新数组也是一样的
console.log(`arr: ${arr}`); // arr: 1,3,4,5,6,7,8
console.log(`newArr: ${newArr}`); // newArr: 1,3,4,5,6,7,8
// 原数组改变,新数组不变
arr.length = 4;
console.log(`arr: ${arr}`); // arr: 1,3,4,5
console.log(`newArr: ${newArr}`); // newArr: 1,3,4,5,6,7,8
shift()
方法的实用性Array.prototype.shift()
这种方法,我们如何[1,2,3,4,5,6] => [2,3,4,5,6]?那就会变得非常麻烦.var arr =[1,2,3,4,5,6];
var newArr = [];
for(var i=0;i<arr.length;i++){
newArr[i]=arr[i+1]
}
newArr=[2,3,4,5,6,] // arr 最后一个数组为null
const Arr = [
{ id: 1, name: 'peng' },
{ id: 0, name: 'zhou' },
{ id: 2, name: 'huang' },
];
// 运用es6的方法轻易做到
const newArr = Arr
.map(e => e.id)
.sort()
.map(id => Arr.find(arr => arr.id === id));
console.log(newArr);
第二种方法
const by = (name, minor) => (o, p) => {
const a = o[name];
const b = p[name];
if (a === b) {
minor(o, p);
}
return a < b ? -1 : 1;
};
// 测试数据
$.ajax({
url: 'https://chat.pipk.top/graphql',
type: 'POST',
dataType: 'json',
data: {
query: `{
search(query:"yinxin630" , type:USER,first:1){
edges{
node{
... on User{
repositories(first:100){
nodes {
forkCount
createdAt
updatedAt
name
}
}
}
}
}
}
}`,
},
success(json) {
const Arr = json.data.search.edges[0].node.repositories.nodes;
// 根据createAt排序,如果createAt相同,则根据forkCount排序
const newArr = Arr.sort(by('createdAt', by('forkCount')));
console.log(newArr);
},
});
const Arr = [1, 2, 3, 4, 23, 5, 5, 5, 6, 6, 4];
const newArr = new Set();
Arr.forEach(arr => newArr.add(arr));
console.log(newArr);