add源码
const NAN=0/0
const INFINITY=1/0
const symbolToString=Symbol.prototype.toString
const toString=Object.prototype.toString
function getTag(value){
if(value==null){ // 判断undefined和null的,在两个等于时undefined和null是相等的
return value===undefined?'[object Undefined]':'[object Null]'
}
return toString.call(value) // 其他的直接返回该类型即可
}
function isSymbol(value){
const type=typeof value
return type=='symbol'||(type==='object'&&value!=null&&getTag(value)=='[object Symbol]')
//这个地方为什么判断这么多,就type的基本就可以保证了吧……
}
function baseToNumber(value){
// 只限制了Symbol
if(typeof value==='number'){
return value
}
if(isSymbol(value)){
return NAN
}
return +value//这个地方就可以转化为数字类型了,如果转化不为正常的数字,为NaN
}
function baseToString(value){
// 也是只限制了Symbol
if(typeof value==='string'){
return value
}
if(Array.isArray(value)){
return `${value.map(baseToString)}`
}
if(isSymbol(value)){
return symbolToString?symbolToString.call(value):""//?是为了判断当前环境?
}
const result=`${value}`
return (result=='0'&&(1/value)==-INFINITY)?'-0':result
//在数字情况下,0,+0,-0,三个是相等的,但是上面的已经为字符串了,字符串是不相等的,且为什么不判断+0?
}
function createMathOperation(operator,defaultValue){
return (value,other)=>{
if(value===undefined&&other===undefined){
return defaultValue
}
if(value!==undefined&&other===undefined){
return value
}
if(other!==undefined&&value===undefined){
return other
}
if(typeof value==='string'||typeof other==='string'){
value=baseToString(value)
other=baseToString(other)
}
else{
value=baseToNumber(value)
other=baseToNumber(other)
}
return operator(value,other)
}
}
const add = createMathOperation((augend,addend)=>augend+addend,0)
console.log(add(1,2))
注意特殊类型null,null == undefined // true,用+(string类型的字符)可以转换为数字