var a = ["a","b","c"]; var b = ["a","b"]; function diff(arr1,arr2){ var newArr = arr1.length>=arr2.length?arr1:arr2.filter(function(ele){ if(arr1.length>=arr2.length?arr2:arr1.indexOf(ele)==-1){ return ele } }) return newArr; }
diff(a,b)
结果是
["a", "b", "c"]
而
a.filter(function(ele){ if(b.indexOf(ele)==-1){ return ele } })
的结果是["c"]
在函数中
arr1.length>=arr2.length?arr1:arr2
结果确实是数组a。
arr1.length>=arr2.length?arr2:arr1
也确实是数组b
但运行结果却是不一样。这是为什么?
因为.运算符的优先级高于:运算符啊,
var newArr = arr1.length>=arr2.length?arr1:arr2.filter实际上是
var newArr = arr1.length>=arr2.length?arr1:(arr2.filter)
你要的是(var newArr = (arr1.length>=arr2.length?arr1:arr2).filter)
看懂了吗?
一周热门 更多>