JS语法_数组
判断数组
// log
let arr = [1, 2, 3]
console.log(typeof arr) // not work
console.log(arr instanceof Array)
console.log(arr.__proto__ === Array.prototype)
console.log(Object.getPrototypeOf(arr) === Array.prototype)
console.log(arr.constructor === Array)
console.log(Array.isArray(arr))
数组方法
forEach
// no-log
Array.prototype.forEach_ = function (cb) {
let len = this.length
for (let i = 0; i < len; i++) {
cb(this[i], i)
}
}
// log
let arr = ['🍉', '🍍', '🍇']
arr.forEach_((item, index) => {
console.log('值:' + item + ' => ' + '索引:' + index)
})
为其加入中止功能
// no-log
Array.prototype.forEach_ = function (cb) {
let len = this.length
for (let i = 0; i < len; i++) {
let result = cb(this[i], i)
if (result === false) {
continue
}
}
}
// log
let arr = [1, 2, 120, 12, 3]
arr.forEach_((item, index) => {
if (item > 100) {
return false
}
console.log(item)
})
push
// no-log
Array.prototype.$push = function () {
for (let i = 0; i < arguments.length; i++) {
this[this.length] = arguments[i]
}
return this.length
}
// log
let arr = [1, 2]
console.log(arr.$push(3, 4))
console.log(arr)
join
join 的效率要比字符串拼接高
// log
let str1 = '1'
let str2 = '2'
let str3 = '3'
let str4 = '4'
let str5 = '5'
let str6 = '6'
let arr = [str1, str2, str3, str4, str5, str6]
let strFinal = ''
function f1() {
for (let i = 0; i < arr.length; i++) {
strFinal += arr[i]
}
}
function f2() {
strFinal += arr.join('')
}
// test +
{
let start = new Date().getTime()
for (let i = 0; i < 100000; i++) {
f1()
}
let end = new Date().getTime()
console.log('字符串拼接耗时: ' + (end - start))
}
// test join
{
let start = new Date().getTime()
for (let i = 0; i < 10000; i++) {
f2()
}
let end = new Date().getTime()
console.log('join耗时: ' + (end - start))
}
类数组
必须有length
属性
// log
let obj = {
1: 'a',
2: 'b',
length: 2,
}
Array.prototype.push.call(obj, 'c')
console.log(obj)
// log
let obj = {
2: 'a',
3: 'b',
length: 2,
push: Array.prototype.push,
}
obj.push('c', 'd')
console.log(obj)
Set
// log
// 去重
function unique(arr) {
return [...new Set(arr)]
}
// 交集
function intersection(arr1, arr2) {
let uniqueArr1 = [...new Set(arr1)]
return uniqueArr1.filter((item) => new Set(arr2).has(item))
}
// 并集
function union(arr1, arr2) {
return [...new Set([...arr1, ...arr2])]
}
// 差集
function diff(arr1, arr2) {
// 交集取反即可
let uniqueArr1 = [...new Set(arr1)]
return uniqueArr1.filter((item) => !new Set(arr2).has(item))
}
let x = [1, 2, 1, 0, 1, 2, 3, 4, 5, 1, 3, 4, 5, 2, 3, 2, 1, 2, 3, 4]
let y = [0, 10, 20, 30, 30, 40, 50]
console.log(unique(x))
console.log(intersection(x, y))
console.log(union(x, y))
console.log(diff(x, y))
console.log(diff(y, x))