把一个字符串13579先变成Array——[1, 3, 5, 7, 9],再利用reduce()就可以写出一个把字符串转换为Number的函数。
function string2int(s) { let arr=s.split(‘‘) arr=arr.map(v=>{ return +v }) return arr.reduce(function(x,y){ return x*10+y }) } //string2int(‘123‘)===123 true
请把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:[‘adam‘, ‘LISA‘, ‘barT‘],输出:[‘Adam‘, ‘Lisa‘, ‘Bart‘]
function normalize(arr){ arr= arr.map((v,index,array)=>{ let str=array[index].substring(1,array[index].length); console.log(‘str‘,str) let a=v[0].toUpperCase()+ str.toLowerCase() return a; }) return arr } if (normalize([‘ADam‘, ‘LISA‘, ‘barT‘]).toString() === [‘Adam‘, ‘Lisa‘, ‘Bart‘].toString()) { console.log(‘通过!‘); } else { console.log(‘失败!‘); } //通过
和map()类似,Array的filter()也接收一个函数。和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是true还是false决定保留还是丢弃该元素。
求100以内素数
function get_primes(arr) { return arr.filter(function(value){ // 1和value本身不用考虑 for(let i=2; i<value; i++){ if(value%i===0){return false;} } return value>1; }); } // 测试: var x, r, arr = []; for (x = 1; x < 100; x++) { arr.push(x); } r = get_primes(arr); if (r.toString() === [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97].toString()) { console.log(‘测试通过!‘); } else { console.log(‘测试失败: ‘ + r.toString()); }
var arra=[7,2,3,0] arra.sort((x,y)=>{ if(x>y){ return 1 } if(x<y){ return -1 } return 0 }) console.log(arra) // [0, 2, 3, 7]
数组Array方法之filter()、map()、sort()、reduce()
原文:https://www.cnblogs.com/sundance123/p/13822347.html