数组的常用方法有哪些?

方法 作用 是否影响原数组
push 在数组后添加元素,返回长度
pop 删除数组最后一项,返回被删项
shift 删除数组第一项,返回被删项
unshift 数组开头添加元素,返回长度
reserve 反转数组,返回数组
sort 排序数组,返回数组
splice 截取数组,返回被截取部分
join 将数组变字符串,返回字符串
concat 连接数组
map 相同规则处理数组项,返回新数组
forEach 遍历数组
filter 过滤数组项,返回符合条件的数组
every 每一项符合规则才返回true
some 只要有一项符合规则就返回true
reduce 接受上一个return和数组下一项
flat 数组扁平化
slice 截取数组,返回被截取区间

forEach 如何跳出循环?

function getItemById(arr, id) {
  var item = null;
  try {
    arr.forEach(function (curItem, i) {
      console.log(i)
      if (curItem.id == id) {
        item = curItem;
        throw Error();
      }
    })
  } catch (e) {}
  return item;
}

清空数组

var arr = [12, 1, 24, -123, 12123123];

arr.length = 0;
// arr.splice(0, arr.length);
// 通过将空数组 [] 赋值给数组(严格意义来说这只是将ary重新赋值为空数组,
// 之前的数组如果没有引用在指向它将等待垃圾回收。)
// arr = [];
console.log(arr);

如何实现数组的随机排序?

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// 随机交换数组内的元素 ✅
function result(arr) {
    for (let i = 0; i < arr.length; i++) {
        // 随机索引【Math.random()返回一个浮点,  伪随机数在范围[0,1)】
        let randomIndex = parseInt(Math.random() * arr.length);
        // 存下当前正常索引值对应的数字
        let curNum = arr[i];
        // 将其重新赋值为随机索引对应的数字
        arr[i] = arr[randomIndex];
        // 将随机索引对应的数字替换为当前正常索引值对应的数字
        arr[randomIndex] = curNum;
    }
    return arr;
}

// sort()可以调用一个函数做为参数,如果这个函数返回的值为负数表示数组中的a项排在b项前
var arr = [1,2,3,4,5,6,7,8,9,10];
arr.sort(() => Math.random() - 0.5)
console.log(arr);

⭐ 对下面数组进行排重,并按升序排序,代码尽量简练:

const array = [ '2', 'b', '9','a','7','3','4','b','6', '4' ];
function handle(arr) {
   // ...your code
}
handle(array); // output: ['2', '3', '4', '6', '7', '9', 'a', 'b']
const array = [ '2', 'b', '9','a','7','3','4','b','6', '4' ];
function handle(arr) {
  return Array.from(new Set(arr))
          .sort((a, b) => a.charCodeAt(0) - b.charCodeAt(0));
}
console.log(handle(array)); // output: ['2', '3', '4', '6', '7', '9', 'a', 'b']

⭐ 自定义 unshift

var arr = [1, 2, 3];

Array.prototype.myUnshift = function() {
  // 在数组打头,添加一个或多个元素,最后返回最新数组的长度
  var len = arguments.length;
  for (let i = len - 1; i >= 0; i--) {
    const element = arguments[i];
    this.splice(0, 0, element);
  }
  return this.length;
}

// console.log(arr.unshift(3, 2, 1), arr);
console.log(arr.myUnshift(3), arr);

⭐ 数组按照元素的总字节数长度排序

var arr = ['Are you OK', 'Lance', 'Jerry', '我爱你'];
// unicode 0-255 1个字节;256 2个字节

var getBytes = function(str) {
	// 先把每个字符都当一个字节算
  var bytes = str.length;

  for (var i = 0; i < str.length; i++) {
  	if (str.charCodeAt(i) > 255) {
    	bytes++;
    }
  }

  return bytes;
}

arr.sort(function(a, b) {
	return getBytes(a) - getBytes(b);
});

// 结果: [ 'Lance', 'Jerry', '我爱你', 'Are you OK' ]

⭐ 数组去重

1. 循环 通过hasOwnProperty判断新数组是否有该属性(问题:{}会被解析成'[object Object]')
var arr = [
  {}, {},
  '', '',
  233, 233, '233',
  'abc',
  undefined,
  null, null,
  NaN, NaN,
  123,
  [2], [2],
  [2, 3]];

Array.prototype.myUnique = function() {
	var hash = {},
      newArr = [];
  for (var i = 0; i < this.length; i++) {
    var item = this[i];
  	if (!hash.hasOwnProperty(typeof item + JSON.stringify(item))) {
    	hash[typeof item + JSON.stringify(item)] = item;
      newArr.push(item);
    }
  }

  return newArr;
};

console.log(arr.myUnique());
// [
//   {},       '',
//   233,      '233',
//   'abc',    undefined,
//   null,     NaN,
//   123,      [ 2 ],
//   [ 2, 3 ]
// ]
2. ES6 Set
Array.prototype.myUnique = function() {
	return Array.from(new Set(this));
};

// [
//   {},        {},
//   '',        233,
//   '233',     'abc',
//   undefined, null,
//   NaN,       123,
//   [ 2 ],     [ 2 ],
//   [ 2, 3 ]
// ]
3. 利用includes检测数组是否有某个值  或者indexOf判断索引
Array.prototype.myUnique = function() {
	let arr = [];
  for (let i = 0; i < this.length; i++) {
    if (!arr.includes(this[i])) {
      arr.push(this[i]);
    }
  }
  return arr;
};

// [
//   {},        {},
//   '',        233,
//   '233',     'abc',
//   undefined, null,
//   NaN,       123,
//   [ 2 ],     [ 2 ],
//   [ 2, 3 ]
// ]