1、如果数组所有元素都满足函数条件,则返回true。调用时,如果省略第二个参数,则默认传递布尔值。
const all= (arr, fn=Boolean) => arr.every(fn); console.log(all([0,1,1])); //false console.log(all([1,2,3]); //true console.log(all([4,5,5,3], x => x>2)); //true
2、判断数组中的元素是否都相等
const allEqual = arr => arr.every(val => val === arr[0]); console.log(allEqual([1,2,3,4,5])); //false console.log(allEqual([1,1,1,1])); //true
3、检查两个数字是否近似相等,差异值可以通过传参的形式进行设置
const approximatelyEqual = (val1, val2, epsilon = 0.001) => Math.abs(val1- val2) < epsilon; console.log(approximatelyEqual(Math.PI / 2, 1.5708));//true
4、将数组中没有逗号或双引号的元素转换成带有逗号分隔符的字符串,即CSV格式识别的形式
const arrayToCSV = (arr, delimiter = ‘,‘) => arr.map(v => v.map(x => `"${x}"`).join(delimiter)).join(‘\n‘); console.log(arrayToCSV([[‘a‘, ‘b‘], [‘c‘, ‘d‘]])); // ‘"a","b"\n"c","d"‘ console.log(arrayToCSV([[‘a‘, ‘b‘], [‘c‘, ‘d‘]], ‘;‘)); // ‘"a";"b"\n"c";"d"‘
5、将数组元素转换成<li>标记,并将此元素添加至给定的ID元素标记内。
const arrayToHtmlList = (arr, listID) => (el => ( (el = document.querySelector(‘#‘ + listID)), (el.innerHTML += arr.map(item => `<li>${item}</li>`).join(‘‘)) ))(); arrayToHtmlList([‘item 1‘, ‘item 2‘], ‘myListID‘);