原生篇
js中有很多隐藏机制,以及接口方法,而很多方法有隐藏坑~
let obj = {
2: 3,
3: 4,
5: 6,
length: 2,
push: Array.prototype.push,
//splice: Array.prototype.splice,
}
obj.push(1) // 相当于obj[2] = 1 obj.length++
obj.push(2) // 相当于obj[3] = 2 obj.length++
console.log(obj) // {2: 1, 3: 2, 5: 6, length: 4, push: ƒ}
// 如果解开注释,则为 Object(4) [empty × 2, 1, 2, 5: 6, push: ƒ, splice: ƒ]数组的push方法原理:在当前length的位置添加指定值,然后length+1,返回新length;如果对象上存在数组原型上的push\splice方法以及length,则数组会被当做伪对象数组
2)
let nums = [1, "12", 3]
nums[4] = 4 // 越length设置,结果为[1,'12',3,empty,4]
nums.unshift(5)
nums.pop()
console.log(nums.length) //5
// unshift在数组前添加 shift弹出数组第一个 push在数组后添加 pop弹出数组最后一个当数组进行越length设置值时,空缺部分会自动补充为empty
3)
function foo1() {
return {
bar: "hello"
};
}
function foo2() {
return
{
bar: "hello"
};
}
console.log(foo1()); // {bar: 'hello'}
console.log(foo2()); // undefinedreturn 后面的内容为返回内容,如果后面内容换行,相当于没有内容,如果没有返回内容则为undefined
4)
console.log(Array(3)); // 输出[empty*3]
console.log(Array(2,3)); // 输出[2,3]Array方法,在传入一个值时代表创建一个传入值长度的空数组;多个值时为从0开始的数组值
5)
var a=[1, 2, 3];
console.log(a.join()); // 输出1,2,3数组原型上的join方法,在不传值时类似于对数组toString
6)
var b = 10;
(function b() {
// 'use strict' //开放又会如何
b = 20
console.log(b) // 输出b方法
})()自执行函数的函数名无法被修改,非严格模式下修改无效,严格模式下报错
7)
'5' + 3 // 53
'5' - 3 // 2+具有拼接字符串和逻辑运算的功能;-只会逻辑运算
8)
typeof null // object
null instanceof Object // falsetypeof对null、对象、数组都会返回object;
9)
Math.min() < Math.max() // falseMath.min方法以最大数Infinity为基准递推出最小数;Math.max则以最小数-Infinity递推出最大数;所以前者比后者大,相当两者在不传参的情况下,min返回Infinity,max返回-Infinity
10)
["1", "2", "3"].map(parseInt) // [1,NaN,NaN]
// 这里map的两个参数默认传递给了parseIntparseInt方法接收两个参数。第一个为字符串,第二个为基数,基数默认为0;基数小于2不包括0或大于36,则返回NaN;map携带两个参数,当前值和当前值下标
11)
[].concat[1,2,3] // undefined()和[]是两个东西
12)
const name = 'TianTianUp'
console.log(!typeof name === 'string') // false
console.log(!typeof name === 'object') // false!typeof xx 和 !(typeof xx)是两个东西,前者将后面内容当做字符串,返回false;后者是判断xx类型再取反
13)
const aa = [] // 引用类型,{}同理
aa.valueOf = function() {
console.log('use it')
};
aa + '1'
aa * 1
Number(aa)引用类型在进行数字处理时(四则运算,转数字等),会隐式触发其原型上的valueOf方法
14)
[] + {} // "[object Object]"
{} + [] // 0
({}) + [] // "[object Object]"
[] + {}:先将[]转为字符串得到结果''+{},然后空字符串与{}相加,{}也被转换为字符串,结果为"[object Object]",最终结果为"[object Object]";{} + []由于{}被放置在最前端,所以被当成了空代码块执行,也就相当于+[],此时[]转换为''。导致最终为+''。结果触发隐式转换,为0;({}) + []为真正的空对象加空数组,相当于例子第一个计算
