Array.prototype.unique = function(){
var arr = [], obj = {};
for(var i = 0; i < this.length; i++){
if(!obj[this[i]]){
arr.push(this[i]);
obj[this[i]] = true;
}
}
return arr;
}
var arr1 = [2, 3, 2, 'hi', 'hi'];
console.log(arr1.unique()); //[2, 3, 'hi']
[2, 4, 1, 3].sort((a,b) => a-b); //[1, 2, 3, 4]
//or
[1,2,3,1,'a',1,'a'].filter(function(v, i, arr){
return i === arr.indexOf(v);
});
_.uniq([2, 3, 2, 'hi', 'hi']); //[2, 3, 'hi']
_.sortBy([2, 4, 1, 3, 3]); //[1, 2, 3, 3, 4]
//排序并去重
_.uniq(_.sortBy([2, 4, 1, 3, 3])); //[1, 2, 3, 4]
[...new Set(array)]
function addUp() {
let total = 0;
for(let num of arguments) {
total += num;
}
return total;
}
addUp(1, 2, 3, 4); // 10
function addUp() {
const nums = Array.from(arguments);
return nums.reduce((prev, next) => prev + next, 0)
}
addUp(1, 2, 3, 4); // 10
// ES5的写法
Math.max.apply(null, [14, 3, 77])
// ES6的写法
Math.max(...[14, 3, 77])
// 等同于
Math.max(14, 3, 77)
// ES5的写法
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
Array.prototype.push.apply(arr1, arr2);
// ES6的写法
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
arr1.push(...arr2);
// or
var arr3 = [...arr1, ...arr2]
<div class="people">
<p>Jayp>
<p>Easonp>
<p>Davidp>
div>
const people = Array.from(document.querySelectAll('.people p'));
const names = people.map(person => person.textContent);
console.log(names); // ['Jay', 'Eason', 'David']