我身在何处?
先给数组排序,然后找到指定的值在数组的位置,最后返回位置对应的索引。
举例:where([1,2,3,4], 1.5) 应该返回 1。因为1.5插入到数组[1,2,3,4]后变成[1,1.5,2,3,4],而1.5对应的索引值就是1。
同理,where([20,3,5], 19) 应该返回 2。因为数组会先排序为 [3,5,20],19插入到数组[3,5,20]后变成[3,5,19,20],而19对应的索引值就是2。
1 /*思路 2 把参数.push()进数组后对数组按升序排序; 3 indexOf()搜索数组中num的位置并返回; 4 */ 5 function where(arr, num) { 6 arr.push(num); 7 arr.sort(function(a, b) { 8 return a - b; 9 }); 10 return arr.indexOf(num); 11 } 12 13 where([40, 60], 50);
freeCodeCamp:Where do I belong
原文:http://www.cnblogs.com/zhouhelong/p/5913483.html